Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must virtual base classes be constructed by the most derived class?

Tags:

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.

like image 332
ネロク・ゴ Avatar asked Jun 02 '17 08:06

ネロク・ゴ


People also ask

What is a virtual base class why it is important to make a class virtual?

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 .

Do all virtual functions need to be implemented in derived classes?

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.

What are the requirements of virtual base class?

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.

What is the purpose of using derived class?

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.


2 Answers

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? }; 
like image 172
Caleth Avatar answered Nov 05 '22 15:11

Caleth


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. 
like image 27
Ajay Avatar answered Nov 05 '22 13:11

Ajay