I have trouble understanding why virtual inheritance is useful in a situation where we do not meet a problem similar to the Diamond Problem when a class inherits from 2 classes derived from the same base class.
Could someone give me an example or explanation when it is still helpful (or needed even)?
Thanks:)
Virtual inheritance isn't really useful when there isn't a potential diamond shape inheritance problem. That problem is what virtual inheritance is all about solving. At cost of weird object layout and having topmost base initialization invoked from most derived class.
The most common practical application of virtual inheritance is for interfaces.
With virtual inheritance you can use the Java technique of inheriting in an implementation.
In C++03 there were additional use cases for virtual inheritance, hacks based on the need for initializing the topmost class from the most derived one.
These use cases included:
Making a class non-inheritable.
Solved by final in C++11.
Forcing use of a specific most-derived class (templated).
In C++11 covariant functionality, such as a clone member function, can more easily be added via middle-man inheritance, with C++11 constructor argument forwarding.
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