I read this question: C++ Virtual class inheritance object size issue, and was wondering why virtual inheritance results in an additional vtable pointer in the class.
I found an article here: https://en.wikipedia.org/wiki/Virtual_inheritance
which tells us:
However this offset can in the general case only be known at runtime,...
I don't get what is runtime-related here. The complete class inheritance hierarchy is already known at compile time. I understand virtual functions and the use of a base pointer, but there is no such thing with virtual inheritance.
Can someone explain why some compilers (Clang/GCC) implement virtual inheritance with a vtable and how this is used during runtime?
BTW, I also saw this question: vtable in case of virtual inheritance, but it only points to answers related to virtual functions, which is not my question.
True enough; so if the compiler knows the type of a most derived object, then it knows the offset of every subobject within that object. For such a purpose, a vtable is not needed.
For example, if
BandCboth virtually derive fromA, andDderives from bothBandC, then in the following code:the conversion from
D*toA*is, at most, adding a static offset to the address.However, now consider this situation:
Here,
fmust be able to accept a pointer to anyBobject, including aBobject that may be a subobject of aDobject or of some other most derived class object. When compilingf, the compiler doesn't know the full set of derived classes ofB.If the
Bobject is a most derived object, then theAsubobject will be located at a certain offset. But what if theBobject is part of aDobject? TheDobject only contains oneAobject and it can't be located at its usual offsets from both theBandCsubobjects. So the compiler has to pick a location for theAsubobject ofD, and then it has to provide a mechanism so that some code with aB*orC*can find out where theAsubobject is. This depends solely on the inheritance hierarchy of the most derived type---so a vptr/vtable is an appropriate mechanism.