Question about Virtual Inheritance hierarchy

Posted by Summer_More_More_Tea on Stack Overflow See other posts from Stack Overflow or by Summer_More_More_Tea
Published on 2010-05-02T16:47:02Z Indexed on 2010/05/03 2:18 UTC
Read the original article Hit count: 221

Filed under:
|

Hi there:

I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class?

By the way, why the output of the following code is:

sizeof(A): 8
sizeof(B): 20
sizeof(C): 20
sizeof(C): 36

Code:

#include <iostream>

using namespace std;

class A{
    char k[ 3 ];
    public:
        virtual void a(){};
};

class B : public virtual A{
    char j[ 3 ];
    public:
        virtual  void b(){};
};

class C : public virtual B{
    char i[ 3 ];
    public:
        virtual void c(){};
};

class D : public B, public C{
    char h[ 3 ];
    public:
        virtual void d(){};
};

int main( int argc, char *argv[] ){
    cout << "sizeof(A): " << sizeof( A ) << endl;
    cout << "sizeof(B): " << sizeof( B ) << endl;
    cout << "sizeof(C): " << sizeof( C ) << endl;
    cout << "sizeof(D): " << sizeof( D ) << endl;

    return 0;
}

Thanks in advance. Kind regards.

© Stack Overflow or respective owner

Related posts about c++

Related posts about virtual-inheritance