Table of virtual functions of multiple inheritance

Sample code is as follows:

class A { public: int k; virtual int f(); }; class B:public virtual A { public: virtual int a(); }; int main() { cout<<sizeof(A)<<sizeof(B); } 

He is typing

8 12

class B seems to have its own new virtual function table.

If class A changes to:

 class A { public: virtual int f(); }; 

He is typing

4 4

Can anyone explain the reason?

+6
source share
2 answers

In your subclass, BB 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 an empty class A, the minimum size allocated to the sizeof A object is a size pointer vtbl = 4 And since A is empty in terms of instance data, virtual inheritance for an empty class does not add to the size of the object

+1
source

In the context of class inheritance, "virtual" means "defined at runtime." There are two separate things that can be virtual, and that the implementation must somehow implement:

  • virtual functions for which the actual function to be called must be determined at runtime: xf() - who is f ? Common implementations include function pointer tables.

  • virtual inheritance in which the virtual base subobject is unknown before execution. The implementation should provide a mechanism for finding the actual base object: xa = 10 - where a ? Common implementations for this include pointer offset calculations.

If the virtual base class has no state (this is similar, but not equivalent, "empty"), then the second use case becomes empty. Since there are no data elements whose location should be determined dynamically, for the implementation it is not required to generate any information for this, nor does it need to store objects of the corresponding links.

One popular C ++ ABI, Itanium ABI, describes in detail how virtuality is implemented . There is also this popular article explaining this implementation.

0
source

Source: https://habr.com/ru/post/974412/


All Articles