[ 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.
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.
Question | |
---|---|
What happens when you call |
GraduateTeachingFellow gtf; Person* pptr = >f; Student * sptr = >f;; Teacher* tptr = >f; 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.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |