dtivmk
asked on
Doubt with multiple inheritance and virtual base classes in C++
The following code prints 20, i.e. sizeof(z) is 20.
#include <iostream.h>
class Base
{
public:
int a;
};
class X:virtual public Base
{
public:
int x;
};
class Y:virtual public Base
{
public:
int y;
};
class Z:public X,public Y
{
};
int main()
{
Z z;
cout << sizeof(z) <<endl;
}
Whereas if I don't use virtual base classes here, i.e. for the following code :
sizeof(z) is 16.
#include <iostream.h>
class Base
{
public:
int a;
};
class X:public Base
{
public:
int x;
};
class Y:public Base
{
public:
int y;
};
class Z:public X,public Y
{
};
int main()
{
Z z;
cout << sizeof(z) <<endl;
}
Isn't it counter intuitive? The main reason for using multiple inheritance
with virtual base classes is to avoid multiple copies of the same Base
class data members. So the sizeof(z) should be lesser in the case
when the virtual classes are being used.
#include <iostream.h>
class Base
{
public:
int a;
};
class X:virtual public Base
{
public:
int x;
};
class Y:virtual public Base
{
public:
int y;
};
class Z:public X,public Y
{
};
int main()
{
Z z;
cout << sizeof(z) <<endl;
}
Whereas if I don't use virtual base classes here, i.e. for the following code :
sizeof(z) is 16.
#include <iostream.h>
class Base
{
public:
int a;
};
class X:public Base
{
public:
int x;
};
class Y:public Base
{
public:
int y;
};
class Z:public X,public Y
{
};
int main()
{
Z z;
cout << sizeof(z) <<endl;
}
Isn't it counter intuitive? The main reason for using multiple inheritance
with virtual base classes is to avoid multiple copies of the same Base
class data members. So the sizeof(z) should be lesser in the case
when the virtual classes are being used.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.