Section 19.11 Multiple Inheritance
In C++, a class can inherit from multiple classes. This is called multiple inheritance. For example, if we had a class
Student
and a class Employee
, we could make a class TeachingAssistant
that inherited from both of them:
class TeachingAssistant : public Student, public Employee {
//...
};
In this case, a
TeachingAssistant
is both a Student
and an Employee
. It would inherit all of the code from both classes and could be treated as either a Student
or an Employee
by other code.
Although this can provide enormous flexibility, it can also lead to complexity and ambiguity, especially if the base classes have members with the same name or descend from a common parent class. Consider what happens if both
Student
and Employee
inherit from a class Person
that has a m_name
:
TeachingAssistant inherits from Student and Employee. They both inherit from Person.
classDiagram class Person { +m_name: string } class Student { +m_major: string } class Employee { +m_salary: double } class TeachingAssistant { +m_subject: string } Person <|-- Student Person <|-- Employee Student <|-- TeachingAssistant Employee <|-- TeachingAssistant
This is known as a “diamond problem” due to the shape of the inheritance diagram. The problem is that a
TeachingAssistant
inherits two copies of m_name
. If we use m_name
inside TeachingAssistant
, it is not clear if we mean Student::m_name
or Employee::m_name
. We can work around this by using the scope resolution operator (::
), but there are still two different m_names
that could be set to completely different values! There are all kinds of potential for confusion and bugs here.
For this reason, many programming languages do not support multiple inheritance, or they provide alternative mechanisms to achieve similar functionality without the associated risks (you can do a web search for “virtual inheritance” to learn about what C++ offers to make multiple inheritance safer). Even when using a language that does support multiple inheritance, many organizations will choose not to make use of it, deeming the added complexity and risk of bugs not worth the flexibility it provides.
You have attempted of activities on this page.