Look at the following C++ code
class Base1 { public: Base1(); virtual ~Base1(); virtual void speakClearly(); virtual Base1 *clone() const; protected: float data_Base1; }; class Base2 { public: Base2(); virtual ~Base2(); virtual void mumble(); virtual Base2 *clone() const; protected: float data_Base2; }; class Derived : public Base1, public Base2 { public: Derived(); virtual ~Derived(); virtual Derived *clone() const; protected: float data_Derived; };
The 《Inside of C++ Object Model 》4.2 says that the virtual table layout of class Base1,Base2 and Derived is like this:
My question is :
The virtual table of the Base1 subObject of class Derived contains Base2::mumble
.Why?I know Derived class shared this virtual table with Base1,so I think the function of Base2 should not appear here.Could someone tell me why? Thx.
Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members.
You can imagine what happens when you perform inheritance and override some of the virtual functions. The compiler creates a new VTABLE for your new class, and it inserts your new function addresses using the base-class function addresses for any virtual functions you don't override.
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.
Well, first of all, I'll remind everyone that the design of the solution to implement polymorphism is an ABI decision outside of the Standard. For example, MSVC and the Itanium ABI (followed by gcc, clang, icc, ...) have different ways to implement this.
With that out of the way, I think that this is an optimization for lookup.
Whenever you have a Derived
object (or one of its descendant) and lookup the mumble
member, you do not need to actually find out the Base2
subobject but can directly act from the Base1
subobject (whose address coincides with Derived
subobject, so no arithmetic involved).
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