The sample code are as follow:
class A
{
public:
int k;
virtual int f();
};
class B:public virtual A
{
public:
virtual int a();
};
int main()
{
cout<<sizeof(A)<<sizeof(B);
}
It prints
8 12
It seems class B
has its own new virtual function table.
If class A
changes to:
class A
{
public:
virtual int f();
};
It prints
4 4
Could anyone explain the reason?
Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances.
Virtual inheritance is a C++ technique that ensures that only one copy of a base class's member variables are inherited by second-level derivatives (a.k.a. grandchild derived classes).
The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object.
Because there are 3 classes here, the compiler will set up 3 virtual tables: one for Base, one for D1, and one for D2. The compiler also adds a hidden pointer to the most Base class that uses virtual functions.
In your subclass B, B is a virtual subclass of A. Thus, B has a separate vtbl pointer (4 bytes) on top of what you have on subobject A. Thus,
sizeof(B object)
= sizeof(A object) + sizeof (vtbl pointer of B)
= sizeof(int) + sizeof (vtbl pointer of A) + sizeof (vtbl pointer of B)
= 4 + 4 + 4
= 12
And,
sizeof(A object)
= sizeof(int) + sizeof (vtbl pointer of A)
= 4 + 4
= 8
If B is a normal subclass of A,
sizeof(B object)
= sizeof(A object)
= sizeof(int) + sizeof (vtbl pointer of A)
= 4 + 4
= 12
For empty class A, minimum size allocated for sizeof A object is sizeof pointer of vtbl = 4 And since A is empty in terms of instance data, virtual inheritance for empty class does not add to size of the object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With