Contents
Should I use virtual inheritance?
In my experience, virtual inheritance (as opposed to virtual methods) is almost never needed. In C++ it’s used to address the “diamond inheritance problem”, which if you avoid multiple inheritance cannot actually happen.
Is virtual inheritance bad?
Virtual inheritance is not a good or bad thing- it is an implementation detail, just like any other, and it exists to implement code where the same abstractions occur.
What is virtual inheritance good for?
Virtual inheritance is a C++ technique that ensures only one copy of a base class’s member variables are inherited by grandchild derived classes. This feature is most useful for multiple inheritance, as it makes the virtual base a common subobject for the deriving class and all classes that are derived from it.
How is virtual inheritance implemented?
When we deal with virtual inheritance, an object of a virtual base class is included into the object of a derived class only once. It is at the end of the XY object that memory for the shared subobject Base is most probable to be allocated. The exact implementation of the class depends on the compiler.
Can multiple inheritance have virtual functions?
You can, however derive non-virtual from A in C and B, but then you have no diamond inheritance anymore. That is, each data-member in A appears twice in B and C because you have two A base-class sub-objects in an D object.
When do you need to use virtual inheritance?
This is something you find may be required if you are using multiple inheritance. In that case it is possible for a class to be derived from other classes which have the same base class. In such cases, without virtual inheritance, your objects will contain more than one subobject of the base type the base classes share.
Why does virtual inheritance cause problems in C + +?
Virtual inheritance causes troubles with object initialization and copying. Since it is the “most derived” class that is responsible for these operations, it has to be familiar with all the intimate details of the structure of base classes.
How does virtual inheritance avoid the diamond problem?
This can be used to avoid the diamond problem by clarifying ambiguity over which ancestor class to use, as from the perspective of the deriving class ( D in the example above) the virtual base ( A) acts as though it were the direct base class of D, not a class derived indirectly through a base ( B or C ).
Which is the most derived class in virtual inheritance?
The “most derived” class XY alone knows where exactly a subobject of the virtual base class Base is to be allocated. That’s why it is the most derived class which is responsible for initializing all the subobjects of virtual base classes. XY constructors initialize the Base subobject and pointers to it in X and Y.