Multiple inheritance

Not everything multiple is as good as it sounds. Multiple inheritance is when a derived class inherits from more than one base class. Usually, this works without a hitch if the multiple base classes we are inheriting from are completely unrelated.

For example, we can have a class Window that inherits from the SoundManager and GraphicsManager base classes. If SoundManager provides a member function playSound() and GraphicsManager provides a member function drawSprite(), then the Window class will be able to use those additional capabilities without a hitch.

Multiple inheritance

Game Window inheriting from Sound Man and Graphics Man means Game Window will have both sets of capabilities

However, multiple inheritance can have negative consequences. Say we want to create a class Mule that derives from both the Donkey and Horse classes. The Donkey and Horse classes, however, both inherit from the base class Mammal. We instantly have an issue! If we were to call mule.talk(), but mule does not override the talk() function, which member function should be invoked, that of Horse or Donkey? It's ambiguous.

private inheritance

A less talked about feature of C++ is private inheritance. Whenever a class inherits from another class publicly, it is known to all code whose parent class it belongs to. For example:

class Cat : public Mammal

This means that all code will know that Cat is an object of Mammal, and it will be possible to point to a Cat* instance using a base class Mammal* pointer. For example, the following code will be valid:

Cat cat;
Mammal* mammalPtr = &cat; // Point to the Cat as if it were a 
                          // Mammal

The preceding code is fine if Cat inherits from Mammal publicly. Private inheritance is where code outside the Cat class is not allowed to know the parent class:

class Cat : private Mammal

Here, externally calling code will not "know" that the Cat class derives from the Mammal class. Casting a Cat instance to the Mammal base class is not allowed by the compiler when inheritance is private. Use private inheritance when you need to hide the fact that a certain class derives from a certain parent class.

However, private inheritance is rarely used in practice. Most classes just use public inheritance. If you want to know more about private inheritance, see http://stackoverflow.com/questions/406081/why-should-i-avoid-multiple-inheritance-in-c.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.62