Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ virtual inheritance

Tags:

Problem:

class Base { public:   Base(Base* pParent);   /* implements basic stuff */ };  class A : virtual public Base { public:   A(A* pParent) : Base(pParent) {}   /* ... */ };  class B : virtual public Base { public:   B(B* pParent) : Base(pParent) {}   /* ... */ };  class C : public A, public B { public:   C(C* pParent) : A(pParent), B(pParent) {} // - Compilation error here   /* ... */ }; 

At the position given, gcc complains that it cannot match function call to Base(), i.e. the default constructor. But C doesn't inherit directly from Base, only through A and B. So why does gcc complain here?

Ideas? TIA /Rob

like image 900
Robert Avatar asked Jan 24 '10 09:01

Robert


People also ask

What does virtual inheritance do?

Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild derived classes.

How does C++ virtual inheritance work?

Virtual inheritance is a C++ technique that ensures that only one copy of a base class's member variables are inherited by second-level derivatives (a.k.a. grandchild derived classes).

Can virtual functions be inherited?

Base classes can't inherit what the child has (such as a new function or variable). Virtual functions are simply functions that can be overridden by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called. A is the base class for B,C,D.

What is virtual base class in inheritance?

Virtual base class in C++ Virtual classes are primarily used during multiple inheritance. To avoid, multiple instances of the same class being taken to the same class which later causes ambiguity, virtual classes are used.


2 Answers

virtual base classes are special in that they are initialized by the most derived class and not by any intermediate base classes that inherits from the virtual base. Which of the potential multiple initializers would the correct choice for initializing the one base?

If the most derived class being constructed does not list it in its member initalization list then the virtual base class is initialized with its default constructor which must exist and be accessible.

Note that a virtual base identifier is allowed to be use in a constructor's initializer list even if it is not a direct base of the class in question.

like image 110
CB Bailey Avatar answered Oct 26 '22 05:10

CB Bailey


You need to explicitly call the constructor for Base from C:

class C : public A, public B { public: C(C* pParent) : Base(pParent), A(pParent), B(pParent) {} /*... */ }; 
like image 40
BenG Avatar answered Oct 26 '22 05:10

BenG