Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is virtual inheritance a good idea?

Tags:

c++

I'm making a game GUI API where each widget inherits from the Widget class. I was thinking, when others make there own widgets, they might not be fully satisfied with the base class. They might want to add getTheme() for example. Would it be a good idea to make all my widgets virtually inherit from Widget then so that this is possible?

Thanks

like image 246
jmasterx Avatar asked Apr 18 '11 14:04

jmasterx


3 Answers

Just because the user would add their own methods to a child class doesn't mean you need to use virtual inheritance. You would use it if, in your library, you have a single base class with multiple children, and people could inherit from multiple child classes at once (for example mixin rather than substitution).

like image 140
Mark B Avatar answered Oct 10 '22 02:10

Mark B


To resolve a diamond-shaped inheritance problem. (B and C both inherit from A. What happens to A's attributes in D that itself inherits from B and C?)

A client of your library could see a RedWidget and a FlyingWidget, and might want to combine them into a RedFlyingWidget.

User would have to specify one of the base classes to be virtual when inheriting. But that is not responsibility of a library maker.

OOP flows better with single-implementation inheritance, so that's what I'd use throughout a library.

There are also "upside-down inheritance" trees, as described by Alexandrescu's excellent "Modern C++ Design." They allow clients to pull in more functionality in a form of mix-ins that are called policies.

Programming with policies allows for greater ability to combine functionality, at the expense of syntactical cleanliness. Think STL implementation, for example.

like image 21
GregC Avatar answered Oct 10 '22 01:10

GregC


When is virtual inheritance a good idea?

That's a design question.

For your Widgets, I would say Yes, multi-derived classes should have the option to be just 1 Widget.

like image 30
Henk Holterman Avatar answered Oct 10 '22 01:10

Henk Holterman