Search code examples
c++multiple-inheritance

Multiple Inheritance : size of class for virtual pointers?


Given the code:

class A{};

class B : public virtual A{};

class C : public virtual A{};

class D : public B,public C{};

int main(){
cout<<"sizeof(D)"<<sizeof(D);
return 0;
}

Output: sizeof(D) 8

Every class contains its own virtual pointer only not of any of its base class, So, why the Size of class(D) is 8?


Solution

  • It depends on compiler implementation. My compiler is Visual Stdio C++ 2005.

    Code like this:

    int main(){
        cout<<"sizeof(B):"<<sizeof(B) << endl;
        cout<<"sizeof(C):"<<sizeof(C) << endl;
        cout<<"sizeof(D):"<<sizeof(D) << endl;
        return 0;
    } 
    

    It will output

    sizeof(B):4
    sizeof(C):4
    sizeof(D):8
    

    class B has only one virtual pointer. So sizeof(B)=4. And class C is also.

    But D multiple inheritance the class B and class C. The compile don't merge the two virtual table.So class D has two virtual pointer point to each virtual table.

    If D only inheritance one class and not virtual inheritance. It will merge they virtual table.