2

Can somebody explain me why the address of an object changes when I cast it to an other parent class type in an diamond inherited class structure?

See this example:

#include <iostream>

class A{
public:
    A(){};
    virtual int a(){
        return 0;
    };
};

class B: virtual public A{
public:
    B(){};
};

class C: virtual public A{
public:
    C(){};
};

class D: public B, public C{
public:
    D(){};
};

 int main(){

     A* a = new D();

     std::cout << "dynamic_cast<A*>: " << dynamic_cast<A*>(a) << std::endl;
     std::cout << "dynamic_cast<B*>: " << dynamic_cast<B*>(a) << std::endl;
     std::cout << "dynamic_cast<C*>: " << dynamic_cast<C*>(a) << std::endl;
     std::cout << "dynamic_cast<D*>: " << dynamic_cast<D*>(a) << std::endl;
     return 0;
 }

The output is:

dynamic_cast<A*>: 0x11e3c20
dynamic_cast<B*>: 0x11e3c20
dynamic_cast<C*>: 0x11e3c28
dynamic_cast<D*>: 0x11e3c20
SucramZ
  • 21
  • 1
  • 5
    Well, what did you expect? You can't have an instance of `B` and an instance of `C` both occupy the same area of memory. That would be particularly obvious if they had data members. – Igor Tandetnik May 13 '17 at 13:52
  • 1
    Note it doesn't require virtual inheritance to get this kind of behavior, just multiple inheritance. – aschepler May 13 '17 at 13:53
  • 1
    [This happens with the simple example `struct A { int a; }; struct B { int b; }; struct C : A, B { int c; };`](http://ideone.com/0o5dyZ) (no diamond inheritance, and no virtual inheritance; just multiple inheritance like @aschepler says). – Cornstalks May 13 '17 at 14:02
  • not a dupe but closely related : http://stackoverflow.com/questions/7845012/why-do-class-members-have-the-same-address-as-their-object – 463035818_is_not_an_ai May 13 '17 at 14:05
  • You may find more information [here](http://stackoverflow.com/q/11603198/218774) – J. Calleja May 13 '17 at 20:54

0 Answers0