Search code examples
c++pointersvirtual

Number of vptr in Virtual Inheritence


i was curious about number of vptr in virtual inheritense. So i write following code for knowing number of vptrs.

class Base
{
    public: virtual void A() { std::cout<<"Base::A()"<<std::endl; }
};

class AnotherBase
{
    public: virtual void B() { std::cout<<"AnotherBase::B()"<<std::endl; }
};

class Child1 : public Base
{
    public: virtual void A() { std::cout<<"Child1::A()"<<std::endl; }
};

class Child2 : public Base
{
    public: virtual void B() { std::cout<<"Child2::B()"<<std::endl; }
};

class Child3 : public virtual Base
{

};

class Child4 : public virtual Base
{
    public: virtual void A() { std::cout<<"Child4::A()"<<std::endl; }
};

class Child5 : public virtual Base
{
    public: virtual void A() { std::cout<<"Child5::A()"<<std::endl; }
    public: virtual void B() { std::cout<<"Child5::B()"<<std::endl; }
};

class Child6 : public Base, public AnotherBase
{

};

class Child7 : public virtual Base, public AnotherBase
{

};

class Child8: public virtual Base, public virtual AnotherBase
{

};

int main() 
{
    using std::cout;
    cout<<"Base    :"<<sizeof(Base)<<std::endl;
    cout<<"Child1  :"<<sizeof(Child1)<<std::endl;
    cout<<"Child2  :"<<sizeof(Child2)<<std::endl;
    cout<<"Child3  :"<<sizeof(Child3)<<std::endl;
    cout<<"Child4  :"<<sizeof(Child4)<<std::endl;
    cout<<"Child5  :"<<sizeof(Child5)<<std::endl;
    cout<<"Child6  :"<<sizeof(Child6)<<std::endl;
    cout<<"Child7  :"<<sizeof(Child7)<<std::endl;
    cout<<"Child8  :"<<sizeof(Child8)<<std::endl;
    return 0;
 }

after running this code i found output as

/* On Visual Studio 2012 */ 
Base    :4
Child1  :4
Child2  :4
Child3  :8
Child4  :8
Child5  :12
Child6  :8
Child7  :12
Child8  :12

i understnd size of Base,Child1 and Child2 are 4 because of vptr
why size of Child3 and Child4 are 8 ? ( I suspect it is a vptr due to virtual inheritence )
why size of Child5 is 12 ? ( I don't know )
why size of Child6 is 8 ( due to vptrs from both base classes )
why size of Child7 is 12 ? ( I guess 8 for two vptr from both base classes each, additional 4 due to virtual inheritense ? )
why size of Child8 is 12 ? ( I don't know )

please explain these questions.

Environment : 64 Bit Windows 7. Visual Studio 2012

I run this code on GCC 4.8.1, i found output as ...

/* On GCC 4.8.1 (Online)*/
Base    :8
Child1  :8
Child2  :8
Child3  :8
Child4  :8
Child5  :8
Child6  :16
Child7  :16
Child8  :16

Now I am total confuse. Why base is 8 byte ?


Solution

  • When we use virtual inheritance, there will be the overhead of 4 bytes (on 32-bit) or 8 bytes (on 64-bit) for a virtual base class pointer in that class.

    The overall size of each class depends on compiler implementation.

    More information can be found here:
    http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible