Virtual base class is a way of preventing multiple instances of a given class appearing in an inheritance hierarchy when using multiple inheritance . Then for the following classes
class level0 {
int a;
public :
level0();
};
class level10:virtual public level0 {
int b;
public :
level10();
};
class level11 :virtual public level0 {
int c;
public :
level11();
};
class level2 :public level10,public level11 {
int d;
public:
level2();
};
I got following sizes of the classes
size of level0 4
size of level10 12
size of level11 12
size of level2 24
but when I removed virtual from inheritance of level10 and level11 I got following output
sizeof level0 4
sizeof level10 8
sizeof level11 8
sizeof level2 20
If virtual inheritance prevents multiple instances of a base class, then why size of classes is greater in case of virtual inheritance?
level0
is larger. As it is, its size gets lost in the noise. Give it 3 or 4int
data members and things will be clearer. – Pete Beckervirtual
, this one has two. The answer uses that singlevirtual
as part of the size description: it wouldn't work as an answer to the above. – Yakk - Adam Nevraumontint
? – David Rodríguez - dribeas