Reputation: 67
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?
Upvotes: 5
Views: 372
Reputation: 585
As you can see in this, it is very clear that if the virtual inheritance is used, the compiler adds one offset pointer to point base class rather than including the base class members in its own memory. That's the reason for increasing size. If it will be x64 bit m\c, pointer size will be 8. And the output will be followings
size of level0 4
size of level10 16
size of level11 16
size of level2 32
Upvotes: 0
Reputation: 101456
Because when using virtual
inheritence, the compiler will create* a vtable to point to the correct offsets for the various classes, and a pointer to that vtable is stored along with the class.
Upvotes: 5