This is what i understood :
During virtual inheritance :virtual base{}
derived class along with inherited data members have to keep vpointer(to keep track of members of base
to keep single instance of members) and one vpointer per inheritance hierarchy that virtually inherits base
are present in derived
class.
In this code with this knowledge:
- sizeof(B) and sizeof(C) then should be = sizeof(A) + vptr
- sizeof(D) should be = sizeof(A) + vptr_from_B + vptr_from_C
struct A{
int i=3,j=1,k=2;
};
struct B: virtual A{};
struct C: virtual A{};
struct D:B,C{};
int main()
{
std::cout<<"size of class D = "<<sizeof(D)<<"\n";
std::cout<<"size of class C = "<<sizeof(C)<<"\n";
std::cout<<"size of class B = "<<sizeof(B)<<"\n";
std::cout<<"size of class A = "<<sizeof(A)<<"\n";
return 0;
}
Case1 :
struct A{}; empty struct
D = 16 , C = 8 , B = 8 , A = 1
Case2 :
struct A{ int i = 3; }; one integer
D = 24 , C = 16 , B = 16 , A = 4
- why B ,C and D have extra 4 bytes ?
Case3 :
struct A{ int i = 3, j = 1; }; two integers
D = 24 , C = 16 , B = 16 , A = 8
- now B, C and D remains of same size even though sizeof A increases by 4 bytes,...?
Case4 :
struct A{ int i = 3, j = 1, k = 2}; three integers
D = 32 , C = 24 , B = 24 , A = 12
- like Case1 we have again 4 bytes extra ?
Pattern continues. . . It feels like some sort of zero padding to keep size of virtually inherited Derived classes multiple of 8, i have no idea what exactly is going on and why ?
sorry for stupid question in advance