Expert C Programming

(Jeff_L) #1

Multiple Inheritance—Deriving from Two or More Base Classes


C makes it easy to shoot yourself in the foot. C++ makes it harder, but when you do, it blows away
your whole leg.


—Bjarne Stroustrup


Multiple inheritance allows two classes to be combined into one, so that objects of the resulting class
would behave as objects of either class. It turns a tree hierarchy into a lattice.


Continuing our Fruit metaphor, we might also have a class Sauces, and note that some objects
that are fruits can also be used as sauces. This gives a type hierarchy featuring multiple inheritance
that can be represented as:


Some likely object declarations would be:


FruitSauce orange, cranberry; // Instances that are sauce and


fruit


Multiple inheritance is much less common than single inheritance, and has been the subject of
considerable debate as to whether it should be in the language at all. It's not in other OOP languages
like Smalltalk. It is in other OOP languages like Eiffel. We should note that, in practice, type
hierarchies tend to look much more like Figure 11-2 than like Figure 11-3.


Figure 11-2. Direct Inheritance

Figure 11-3. Multiple Inheritance
Free download pdf