3

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

Vijay M M
  • 81
  • 6
Akshatha
  • 39
  • 4
  • 1
    Why is this closed as duplicate? Linked question only explains that there is virtual pointer which is inherited, that's all. It does not explain why **size of D is 2 when inheriting from empty classes** as in first example, nor why **size of D in second example is 16 instead of 8 if there should be only one virtual pointer inherited from B**. It should be "reopened", because **it's not duplicte**. – PcAF Jun 13 '16 at 07:52

0 Answers0