The following code won't compile:
class A { public: A(int) {} }; class B: virtual public A { public: B(): A(0) {} }; // most derived class class C: public B { public: C() {} // wrong!!! };
If I call A
's constructor in C
's constructor initialization list, that is:
// most derived class class C: public B { public: C(): A(0) {} // OK!!! };
it does work.
Apparently, the reason is because virtual base classes must always be constructed by the most derived classes.
I don't understand the reason behind this limitation.
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. Need for Virtual Base Classes: Consider the situation where we have one class A .
Derived classes do not have to implement all virtual functions themselves. They only need to implement the pure ones. That means the Derived class in the question is correct.
Need for Virtual Base Class in C++Only one copy of its data members is shared by all the base classes that use the virtual base class. If a virtual base class is not used, all the derived classes will get duplicated data members. In this case, the compiler cannot decide which one to execute.
Derived classes are used for augmenting the functionality of base class by adding or modifying the properties and methods to suit the requirements of the specialization necessary for derived class.
Because it avoids this:
class A { public: A(int) {} }; class B0: virtual public A { public: B0(): A(0) {} }; class B1: virtual public A { public: B1(): A(1) {} }; class C: public B0, public B1 { public: C() {} // How is A constructed? A(0) from B0 or A(1) from B1? };
Because in the class hierarchy having a virtually inherited base class, the base class would/may be shared by multiple classes (in diamond inheritance for example, where the same base class is inherited by multiple classes). It means, there would be only one copy of the virtually-inherited base class. It essentially means, the base class must be constructed first. It eventually means the derived class must instantiate the given base class.
For example:
class A; class B1 : virtual A; class B2 : virtual A; class C: B1,B2 // A is shared, and would have one copy only.
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