Search code examples
c++inheritancevirtual

Questions about C++ virtual Inheritance


The following code are from the book "Inside the C++ object model"

#include <iostream>  
using namespace std;
class X{};
class Y: public virtual X{};
class Z: public virtual X{};
class A: public Y, public Z{};

int main()
{
     cout<<sizeof(X)<<" "<<sizeof(Y)<<" "<<sizeof(Z)<<" "<<sizeof(A)<<endl;
     return 0;
}

In my computer(Windows, VS2010), the output is:

1 4 4 8

Here're my questions

1, sizeof(X)=1

The book says when X type generate two instance, say xa and xb. the compile insert a byte into A so that xa and xb can have different address. I'm not quite understand the reasons.

2, sizeof(Y)=4

By using virtual inheritance, will we have an additional virtual pointer? I guess this might be different from virtual pointer in polymorphism. Can anyone give me the memory layout for Y?

Thank you!


Solution

    1. compiler new one char when the class is empty, so it can generate different object
    2. sizeof(Y)=4 because it's virtual inheritance, construct will generate vptr table which is 4 bytes on 32-bit system
    3. if you are using visual studio use /d1reportAllClassLayout in properties->C/C++/Command to generate object layout class Y object layout will be on Visual Studio:
    4. book 'Inside C++ object model' by Stanley B. Lippman explained this extremely well

     
            class Y size(4):
                +---
                0     | {vbptr}
                +---
                +--- (virtual base X)
                +---
    Y::$vbtable@: 0 | 0 1 | 4 (Yd(Y+0)X)

    vbi: class offset o.vbptr o.vbte fVtorDisp X 4 0 4 0