When is virtual inheritance a good idea?

I am creating a GUI API where each widget is inherited from the Widget class. I thought when others create their own widgets, they may not be completely satisfied with the base class. They might want to add getTheme (). Would it be a good idea to make all of my widgets actually inherited from Widget so that this is possible?

thanks

+6
source share
4 answers

Just because the user will add their own methods to the child class does not mean that you need to use virtual inheritance. You would use it if in your library you have one base class with several children, and people can inherit several child classes at once (for example, mixin instead of replacing).

+4
source

To solve the problem of inheritance in the form of a diamond. (B and C both inherit from A. What happens to attributes A in D, which themselves inherit from B and C?)

Your library client may see RedWidget and FlyingWidget and may want to combine them into RedFlyingWidget.

The user must specify that one of the base classes be virtual when inheriting. But this is not the responsibility of the creator of the library.

OOP streams are better with single-implementation inheritance, so I would use the whole library.

There are also trees with inverted inheritance, as described by Alexandrescu perfectly " Modern C ++ Design ." They allow customers to use more functionality in the form of mixing, which are called policies.

Policy-based programming enhances the ability to combine functionality through syntactic cleanliness. For example, consider implementing an STL.

+4
source

When is virtual inheritance a good idea?

This is a design issue.

For your widgets, I would say yes, several derived classes should have the ability to be just one widget.

+1
source

Whenever users of your library are going to use several classes from your library as a base class (i.e., get from them), you should use virtual inheritance. In other words, it is a good idea to use it in your case.

0
source

Source: https://habr.com/ru/post/886154/


All Articles