C++ Programming: Cross Casts

A multiply inherited class object can be converted into a second base class.

For ex:

struct A
int i;
virtual ~A () {}

struct B { bool b; };

struct D: public A, public B
int k;
D() { b = true; i = k = 0; }

A *ptra = new D;
B *ptrb = dynamic_cast< B* >ptra;

The static type for ptra is A * where as the dynamic type is D *. Normal static cast can't be used here as A and B are two different structures. reinterpret_cast<> will result in simply assigning ptra to ptrb. But the address of B subobject and A subobject in D are different. So to do so we have to calculate the address of B at runtime which can be achieved by dynamic_cast<>


About this entry