Jump to content

Virtual inheritance

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by BenFrantzDale (talk | contribs) at 05:15, 19 May 2005 (A start.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

You must add a |reason= parameter to this Cleanup template – replace it with {{Cleanup|reason=<Fill reason here>}}, or remove the Cleanup template.

In object-oriented programing languages, virtual inheritance solves some of the problems caused multiple inheritance by having common grandparent classes used only once. It usually is used when the inheritance is representing restrictions of a set rather than composition of parts.

In C++, virtual inheritance is indicated by the virtual keyword. For example:

class Animal {
  virtual void Eat();
};
// Two classes virtually inheriting TheCommonBase:
class Mammal : public virtual Animal {
  virtual const Color GetHairColor() const;
};
class WingedAnimal : public virtual Animal {
  virtual void Flap();
};
// A bat can Eat
class Bat : public Mammal, public WingedAnimal {};

In the above, if Mammal and WingedAnimal did not inherit virtually, a call to Bat::Eat() would be ambiguous and hence a compile error.