I wanted to know the ordering of member variables and vtable pointers in C++ on a diamond virtual inheritance.
Consider the below inheritance:
class Base
{
int b;
};
class Derived: public virtual Base
{
int d;
};
class Derived2: public virtual Base
{
int d2;
};
class Derived3: public Derived, public Derived2
{
int d3;
};
I wanted to know the memory layout of class Derived3. I looked at following links online:
c++ data alignment /member order & inheritance
After going through the above links this is what I feel the memory layout of Derived3 could be:
void* vtable_ptr1 //vtable pointer of Derived
int d //Derived
void* vtable_ptr2 //vtable pointer of Derived2
int d2 //Derived2
int b //Base? not sure where will this be.
int d3 //Derived3
Online compilers give the size of Derived3 as 40 bytes, so I feel (assuming 8 bytes for pointer and 4 bytes for int) int b has to come after vtable_ptr2 (8(vtable_ptr1) + 4(d) + [4 padding] + 8(vtable_ptr2) + 4(d2) + 4(b) + 4(d3) + [4 class padding]) or before vtable_ptr1 (4(b) + [4 padding] + 8(vtable_ptr1) + 4(d) + [4 padding] + 8(vtable_ptr2) + 4(d2) + 4(d3)) so that padding comes into picture and increases the size of the class to 40.
To summarize, I have the following question:
Is the ordering correct? If not, what is the correct ordering of member variables and vtable pointers?