Multiple Inheritance

In a previous post I discussed the Object Oriented Programming concept of Inheritance.  This post will discuss Multiple Inheritance.  Multiple Inheritance is the concept of an object deriving itself from multiple super classes.  Not all programming languages support this Multiple Inheritance . Objective C would be a language that do NOT support Multiple Inheritance while C++ does.

A person could have multiple traits. Not every person would share the same traits.  Traits, like Creative, Happy, Strong could be modeled as small objects.  A Person object would be derived from these smaller object to create a “CreativeHappyStrongPerson“.  Problems could arise when we have a “CreativeHappySadPerson“.  This is because there could be a conflict in how certain behaviors would react.  How would a happy and sad person react to say a particular task which is dependent on the Person’s mood.  Without getting into the psychology of the problem, this fictitious example is trying to demonstrate the complexities of Multiple Inheritance.

Diamond Problem
There is also nothing to stop an object from inheriting from multiple objects that share the same base class.  This problem is known as the diamond problem.  The diamond problem leads to the possible issues:

  • ambiguity when virtual methods in the base class are overridden
  • duplicated members from the common base class that co-exist in the object that is derived with multiple inheritance

Here is a good blog post that discusses the Diamond problem that arises with virtual Inheritance and presents solutions.

Composition

Thought, multiple inheritance has its purpose it should be used only when really needed.  In most cases try to model the problem with composition rather then with multiple inheritance.  Composition defines the other types of relationship in OOP which is the “has a relationship“.

Take our example above with the CreativeHappySadPerson.  We can model this problem with composition.  A Person object could store a container of emotions instead.  The user of the object would then be forced to access a defined emotion removing ambiguity.

References

Here is a good reference that I found on Stack Overflow that discusses the downfalls of Multiple Inheritance.

Advertisements
This entry was posted in Development. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s