- Multiple Inheritance refers to a class can inherit features and data members from multiple classes. For example, we have class Animal, Mammal and Carnivore. Mammal and Carnivore both derived from Animal. We further have a class Tiger inheriting both Mammal and Carnivore. For example,
Animal (eat())
/ \\ /
Mammal (eat()) Carnivore (eat())
Tiger (eat())
- If we have the above inheritance hierarchic, if the base class Animal has a virtual method eat(), both Mammal and Carnivore will have its eat(), which lead to that in the Tiger class, when its instance call eat(), it doesn't know which one to call. It can only call t.Mammal::eat() or t.Carnivore::eat(). In order to solve this Diamond problem, Virtual Inheritance is introduced. If we have "class Mammal :: public virtual Animal" and "class Carnivore :: public virtual Animal", then for the later Tiger class, we won't have this ambiguity.
- When you use Private Inheritance (e.g., class A :: private B), all the public methods and data members in B will be private after inheritance. This is so called "Implement A in term of B". And the implementation of B is not exposed after private inheritance. A better way is to use "Inclusion", try to make B a private data member of A. For certain situation, inclusion is not possible, so you have to use private inheritance.
No comments:
Post a Comment