In what scenarios can be reinterpret_cast used to cast from a base pointer that’s actually a derived instance pointer? (via polymorphism).
Static casts do not work if the inheritance is polymorphic.
I considered this trivial scenario:
class A
{
public:
virtual void Hello()
{
cout<<" A ";
}
virtual int GetType() { return 1; }
};
class B: public A
{
public:
void Hello()
{
cout<< " B ";
}
void Do()
{
cout << " Another method of B";
}
int GetType() { return 2;}
};
/// ... sample/test code
A* a1 = new A();
A* b1 = new B();
A* a2;
B* b2;
if (a1->GetType() == 1)
{
a2 = a1;
a2->Hello();
}
else
if (a1->GetType() == 2)
{
b2 = reinterpret_cast<B*>(a1);
b2->Do();
b2->Hello();
}
Mind the very naive “pseudo type identification method GetType() ) I used to decide whether I can convert them or not. Is it downright wrong to use reinterpret_casts at all, for such purposes, of avoid dynamic_casts? (i.e. is it a paranoic design, inherently dangerous and less flexible that can introduce unwanted trouble? Might it be safer and worth the minor performance cost to perform normal dynamic casts? I know that multiple inheritance and/or virtual inheritance will mess up any other cast operation, except for the polymorphic/dynamic one).
You can’t use
reinterpret_castto downcast safely. But you can usestatic_cast, when you know that the dynamic type of the object is (possibly derived from) the one you cast down to, anddynamic_cast, of reference or pointer, if the statically known class is polymorphic.In the other direction, for an upcast you can (but should not) use a C style cast in order to cast to an inaccessible base. It’s specially supported in the standard. I have never found occasion to use it, though.