22.3.3. Resolving Multiple Inheritance Conflicts

[ fromfile: multiple-inheritance.xml id: multinheritanceconflicts ]

Figure 22.4 shows a UML diagram where multiple inheritance is used incorrectly for both interface and implementation. To make things even more complicated, one class inherits from the same base class twice.

Figure 22.4. Person - Student - Teacher

Person - Student - Teacher

Here, the class GradTeachingFellow is derived from two classes: Student and Teacher.

class GradTeachingFellow : public Student,
                           public Teacher {
     // class member functions and data members
};

Name conflicts and design problems can arise from the improper use of multiple inheritance. In this example, getDepartment() function exists in both Student and Teacher. The student could be studying in one department and teaching in another, for example.

[Important] Question

What happens when you call getDepartment() on a GraduateTeachingFellow?

   GraduateTeachingFellow gtf;
   Person* pptr = &gtf;
   Student * sptr = &gtf;;
   Teacher* tptr = &gtf;
   gtf.Teacher::getDepartment();
   gtf.Student::getDepartment();
   sptr->getDepartment()
   tptr->getDepartment()
   pptr->getDepartment();   // Ambiguous: runtime error if virtual
   gtf.getDepartment();  // Compiler error: ambiguous function call

The problem, of course, is that we have provided no getDepartment() function in the GradTeachingFellow class. When the compiler looks for a getDepartment() function, Student and Teacher have equal priority.

Inheritance conflicts like these should be avoided because they lead to great design confusion later. However, in this case they can also be resolved with the aid of scope resolution.