Search code examples
c++inheritancevirtual

Why size of classes is larger in case of virtual inheritance?


Virtual base class is a way of preventing multiple instances of a given class appearing in an inheritance hierarchy when using multiple inheritance . Then for the following classes

class level0 {
    int a;
    public :
    level0();
};

class level10:virtual public level0 {
    int b;
    public :
    level10();
};

class level11 :virtual public level0 {
    int c;
    public :
    level11();
};

class level2 :public level10,public level11 { 
    int d;
    public:
    level2();
};

I got following sizes of the classes

size of level0 4

size of level10 12

size of level11 12

size of level2 24

but when I removed virtual from inheritance of level10 and level11 I got following output

sizeof level0 4

sizeof level10 8

sizeof level11 8

sizeof level2 20

If virtual inheritance prevents multiple instances of a base class, then why size of classes is greater in case of virtual inheritance?


Solution

  • Because when using virtual inheritence, the compiler will create* a vtable to point to the correct offsets for the various classes, and a pointer to that vtable is stored along with the class.


    • "Will create" -- vtables are not dictated by the Standard, but the behaviors implied by virtual inheritence is. Most compilers use vtables to implement the functionality dictated by the Standard.