If I run the following code, I get different addresses. Why?
Because the Base2 sub-object of the Base2 object is not at the beginning of the Derived object. Thus, the addresses are different. When the compiler performs an implicit conversion from Derived* to Base2* , it needs to configure the address.
Given the definitions of the Base1 and Base2 , both sub-objects of the Derived class cannot be on the starting address of the Derived object - there is no place in this address for both subtexts -Objects.
Let's say you have this code:
Derived* d = new Derived; Base1* pb1 = d; Base2* pb2 = d;
How would it be possible for pb1 and pb2 point to the same address? pb1 must point to an element of Base1::x , and pb2 must point to an element of Base2::y (and these elements must be different).
Even more fun, if you repeatedly enter and exit the union, the address continues to increase by 4
Since you read the union d member after writing the b member, which is undefined (you essentially do something like reinterpret_cast<Derived*>() on Base2* ).
I want him to leave my pointers alone.
Not if you want a Base2* pointer. Multiple inheritance makes things more complicated - so many people suggest avoiding this if absolutely necessary.
source share