My earlier comment was taken somewhat out of context.
I later went on to say that C style casts are an unholy mesh of static,reinterpret,const casts. Sometimes you get one, sometimes you get another.
- you may not remove constness with static_cast, |
You can't with reinterpret_cast either, can you?
- you may not cast completely unrelated types this way (like int* to double*) |
But you can do other static casts, such as int to double.
correctly handles multiple inheritance |
I thought it behaved like static_cast in that instance. I came to this assumption because implicit upcasting behaves like static_cast.
I never did actually test it, granted, so I could be wrong. I'd be VERY surprised if it acted like reinterpret_cast though.
I'll test this when I get home.
EDIT:
I was right. C casts behave like static cast when multiple inheritance is involved:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
using namespace std;
class A { int a; };
class B { int b; };
class C : public A, public B { int c; };
int main()
{
C obj;
B* b = &obj;
A* a = &obj;
//=============
cout << "Casting from A:\n";
cout << "reinterpret: " << reinterpret_cast<C*>(a) << "\n";
cout << "static: " << static_cast<C*>(a) << "\n";
cout << "C style: " << (C*)(a) << "\n";
cout << "\n\n";
//=============
cout << "Casting from B:\n";
cout << "reinterpret: " << reinterpret_cast<C*>(b) << "\n";
cout << "static: " << static_cast<C*>(b) << "\n";
cout << "C style: " << (C*)(b) << "\n";
cout << "\n\n";
char c;
cin >> c;
return 0;
}
|
Casting from A:
reinterpret: 0xbfd7585c
static: 0xbfd7585c
C style: 0xbfd7585c
Casting from B:
reinterpret: 0xbfd75860
static: 0xbfd7585c
C style: 0xbfd7585c |
So to recap... C casts are just like static_cast except for the following:
- can cast between pointers of unrelated types (here, C casts behave like reinterpret_cast)
- can cast away const/volatile modifiers (here, C casts behave like const_cast)