Search code examples
c++sizeofvirtual-inheritancememory-layoutvptr

size of derived class in virtual inheritance


#include "stdafx.h"
#include <iostream>
using namespace std;

class ClassA
{
    protected:
       int width, height;
    public:
       void set_values(int x, int y)
       {
         width = x;
         height = y;
       }
};

class ClassB : virtual public ClassA
{
   //12(int + int + vptr)
};

class ClassC : virtual public ClassA
{
  //12(int + int + vptr)
};

class ClassD : public ClassB, public ClassC
{
};

int main()
{
  ClassA A;
  ClassB B;
  ClassC C;
  ClassD D;
  cout << "size = " << sizeof(A) << endl;
  cout << "size = " << sizeof(B) << endl;
  cout << "size = " << sizeof(C) << endl;
  cout << "size = " << sizeof(D) << endl;
  return 0;
}

the output i got is:

size of ClassA = 8
size of ClassB = 12
size of ClassC = 12
size of ClassD = 16

In the above code why the output is 16 for ClassD. please explain me clearly how this virtual inheritance works.


Solution

  • Virtual inheritance means, that the virtual base classes only exist once instead of multiple times. That is why the 8 bytes from ClassA are only in ClassD once. Virtual inheritance itself requires a certain overhead and hence you get an additional pointer. The exact implementation and therefore the exact overhead is not specified by the C++ standard and may vary depending on the hierarchy you are creating.