◄Up► ◄Contents► ◄Index► ◄Back► ─────C/C++ Language───────────────────────────────────────────────────────── Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use multiple inheritance. Consider the following example: class Employee { private: char name[30]; }; class SalesPerson : public Employee { }; class Manager : public Employee { }; class SalesManager : public SalesPerson, public Manager { }; In this hierarchy, the Employee class acts as an indirect base class to SalesManager twice. The following diagram describes a SalesManager object: Employee Employee │ │ SalesPerson Manager \ / SalesManager Each SalesManager object contains two copies of the data members defined in Employee. This duplication wastes space and requires you to specify which copy of Employee's members you want whenever you access them. The use of the virtual keyword eliminates these problems. When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use it as a virtual base. For example: class Employee { private: char name[30]; }; class SalesPerson : virtual public Employee { }; class Manager : virtual public Employee { }; class SalesManager : public SalesPerson, public Manager { }; A SalesManager object can now be described by the following diagram: Employee / \ SalesPerson Manager \ / SalesManager The SalesPerson and Manager base classes share the same copy of Employee's data members. As a result, each SalesManager object contains just one copy of Employee's data members, and references to Employee's members are unambiguous. Notice that the virtual keyword appears in the base lists of the SalesPerson and Manager classes, not SalesManager. -♦-