Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function table of multiple inheritance

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?

like image 551
maple Avatar asked Aug 27 '14 08:08

maple


People also ask

Can multiple inheritance have virtual classes?

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.

What are multiple inheritances virtual inheritance )?

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).

What is VPTR and V table?

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.

How many virtual function tables are there?

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.


1 Answers

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

like image 109
Dr. Debasish Jana Avatar answered Oct 05 '22 13:10

Dr. Debasish Jana