|
Article on other languages:
|
In the C++ programming language, virtual inheritance is a kind of inheritance that solves some of the problems caused by multiple inheritance (particularly the "diamond problem") by clarifying ambiguity over which ancestor class members to use. It is used when inheritance is representing restrictions of a set rather than composition of parts. A multiply-inherited base class is denoted as virtual with the
The problemConsider the following class hierarchy. class Animal { public: virtual void eat(); }; class Mammal : public Animal { public: virtual Color getHairColor(); }; class WingedAnimal : public Animal { public: virtual void flap(); }; // A bat is a winged mammal class Bat : public Mammal, public WingedAnimal {}; Bat bat; But how does This situation is sometimes referred to as diamond inheritance because the inheritance diagram is in the shape of a diamond. Virtual inheritance can help to solve this problem. Class representationBefore going further it is helpful to consider how classes are represented in C++. In particular, inheritance is simply a matter of putting parent and child class one after the other in memory. Thus Bat is really (Animal,Mammal,Animal,WingedAnimal,Bat) which makes Animal duplicated, causing the ambiguity. SolutionWe can redeclare our classes as follows: // Two classes virtually inheriting Animal: class Mammal : public virtual Animal { public: virtual Color getHairColor(); }; class WingedAnimal : public virtual Animal { public: virtual void flap(); }; // A bat is still a winged mammal class Bat : public Mammal, public WingedAnimal {}; Now the This is implemented by providing See also |
This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License.
Mercedes Car
This site monitored by SitePinger.net