answersLogoWhite

0

Consider the following class declarations:

class Base{...};

class Intermediate1: public Base{...};

class Intermediate2: public Base{...};

class Derived: public Intermediate1, public Intermediate2{...};

Here, Derived indirectly inherits two instances of Base, one from Intermediate1 and the other from Intermediate2. This introduces an ambiguity when implicitly referring to Base from Derived. We must explicitly refer to Intermediate1::Base or Intermediate2::Base. Not only that but since there are two instances of Base, they consume twice as much memory.

Clearly it would be better if there were only one instance of Base shared between Intermediate1 and Intermediate2. This isn't always possible, but if we assume that it is possible in this case, we need to allow Derived to inherit directly from Base and for Intermediate1 and Intermediate2 to both share that same instance, virtually. We do this by declaring Base to be virtually inherited by both Intermediate1 and Intermediate2:

class Base{...};

class Intermediate1: public virtual Base{...};

class Intermediate2: virtual public Base{...};

class Derived: public Intermediate1, public Intermediate2{...};

Now there's only one instance of Base which is directly inherited by Derived. Thus when Derived, Intermediate1 or Intermediate2 implicitly refer to their Base class, they will implicitly refer to Derived::Base. Moreover, any objects we subsequently derive from Derived will inherit directly from Base themselves, but it remains the one and only instance of Base in the hierarchy.

Note that the virtual keyword can be placed before or after the access specifier, it makes no difference (both methods are shown above). Note also that the virtual keyword is only of relevance to Derived and its derivatives. It does not affect any non-derived instances of Intermediate1 nor Intermediate2 -- they still inherit directly from Base.

I mentioned earlier that it isn't always possible to make use of virtual base classes. It all depends on the purpose of the classes involved and what members they have. Generally, the fewer members in the base class the better, so abstract base classes are often good candidates for virtual base classes. Ultimately, all derivatives must be capable of sharing the same instance of the virtual base class.

User Avatar

Wiki User

12y ago

What else can I help you with?