Multiple Inheritance – Use Cases and Examples

multiple-inheritance

Java omits multiple inheritance on the grounds that it obviates the design goal of keeping the language simple.

I wonder if Java (with its eco-system) is really "simple". Python is not complex and has multiple inheritance. So without being too subjective, my question is…

What are the typical problem patterns that benefit from a code designed to make heavy use of multiple inheritance

Best Answer

Pros :

  1. It sometimes allow more obvious modeling of a problem than other ways to model it.
  2. If the different parrents have orthogonal purpose, it can allow some kind of compositing

Cons :

  1. If the different parents don't have orthogonal purpose, it makes the type difficult to understand.
  2. It's not easy to understand how it is implemented in a language (any language).

In C++ a good example of multiple inheritance used to composite orthogonal features is when you use CRTP to, for example, setup a component system for a game.

I've started to write an example but I think a real world example is more worth looking at. Some code of Ogre3D uses multiple inheritance in a nice and very intuitive way. For example, the Mesh class inherit from both Resources and AnimationContainer. Resources expose the interface common to all resources and AnimationContainer expose the interface specific for manipulating a set of animations. They are not related, so it's easy to think about a Mesh as being a resource that in addition can conain a set of animations. Feels natural isn't it?

You can look at other examples in this library, like the way memory allocation is managed in a fined grain way by making classes inherit from variants of a CRTP class overloading new and delete.

As said, the main problems with multiple inheritance rises from mixing related concepts. It makes the language have to set complex implementations (see the way C++ allows to play with the diamond problem...) and the user not being sure what's happening in that implementation. For example, read this article explaining how it is implemented in C++.

Removing it from the language helps avoiding people who don't know how the language is inforced to make things bad. But it forces to think in a way that, sometimes, don't feel natural, even if it's edge cases, it happen more often that you might think.