I have executed below code where the size of class A, B and C are 1, which makes sense because size of an empty class is 1. But size of D is 2. How is this possible?
class A{};
class B : public A{};
class C : public A{};
class D : public B, public C{};
int main()
{
cout<<"Size of A is "<<sizeof(A)<<endl;
cout<<"Size of B is "<<sizeof(B)<<endl;
cout<<"Size of C is "<<sizeof(C)<<endl;
cout<<"Size of D is "<<sizeof(D)<<endl;
return 0;
}
Output Size of A is 1, Size of B is 1, Size of C is 1, Size of D is 2
Also when I executed below code size of class A is 1(Empty class) size of B is 8(due to virtual inheritance we will have Vptr so size is 8), size of C is 1(Empty class). But why the size of D is 16 even though C is not virtually inherited.
class A{};
class B : virtual public A{}; //Virtual Inheritance
class C : public A{}; //No Virtual Inheritance
class D : public B, public C{};
int main()
{
cout<<"Size of A is "<<sizeof(A)<<endl;
cout<<"Size of B is "<<sizeof(B)<<endl;
cout<<"Size of C is "<<sizeof(C)<<endl;
cout<<"Size of D is "<<sizeof(D)<<endl;
return 0;
}
Output Size of A is 1, Size of B is 8, Size of C is 1, Size of D is 16
Please help me to understand this. Thanks in advance