I'm in the process of developing a framework for our internal use and thought making all inheritance virtual would avoid the diamond problem for other developers inheriting from my classes.
I looked around and found a lot of discussion on using virtual inheritance WHEN faced with the diamond issue, but nothing about preempting it.
Virtual inheritance is used when we are dealing with multiple inheritance but want to prevent multiple instances of same class appearing in inheritance hierarchy. From above example we can see that “A” is inherited two times in D means an object of class “D” will contain two attributes of “a” (D::C::a and D::B::a).
The answer is definitely no. The base of an idiomatic answer can be the most fundamental idea of C++: you only pay for what you use. And if you don't need virtual inheritance, you should rather not pay for it. Virtual inheritance is almost never needed.
If you don't use virtual functions, you don't understand OOP yet. Because the virtual function is intimately bound with the concept of type, and type is at the core of object-oriented programming, there is no analog to the virtual function in a traditional procedural language.
Virtual base class in C++ 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.
Which of the following statements about virtual inheritance is correct? Yes, we can access the base class from a derived class that is why there is no use of creating an object of the base class.
Virtual inheritance solves the classic “Diamond Problem”. It ensures that the child class gets only a single instance of the common base class. In other words, the Snake class will have only one instance of the LivingThing class. The Animal and Reptile classes share this instance.
Remember that with non-virtual inheritance, each constructor calls the constructors of just immediate base classes. But with virtual inheritance, the most derived class needs to call the constructors of all virtual base classes.
If your base classes need initialization, virtual inheritance will mean every class down the tree will need to correctly initialize it. And any class in the middle of the tree can't count on its own base class being initialized the way it would like.
Just what I found in the Standard:
static_cast
to convert to a derived class reference/pointer if there's virtual inheritance involved. [expr.static.cast]/2, 11this
[basic.life]/5,6.Depending on the implementation of virtual base classes, there might be other drawbacks.
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