I know how data will be packed is not specified by the standard. I was just trying to get an idea about the memory layout of classes ( esp. how dynamic_cast<void*>
guarantees to return a pointer to the start of the most derived class). I could not think of any explanation about the output of the following code:
struct A{ int a;};
struct B{ int b;};
struct C: public A, public B { int c;};
struct D:public C {int d;};
int main(){
D* ob=new D;
A* a = ob;
B* b = ob;
C* c = ob;
}
Printing the values of the pointers shows that, a
,c
,d
have always same value, only b
is added 4 Bytes as offset. Is it accidental? Or there is a logic behind it?
Edit:
Conceptually the layout should be like the image,but somehow the points A,C and D merges to one.