Be aware of problems with virtual bases

When using virtual bases, be aware of these multiple inheritance problems (a Taligent engineer must confirm with an architect before using multiple inheritance):

Virtual bases can be confusing and hard to understand: Try to avoid getting into a situation where you have a virtual base; no matter which alternative you choose, programmers tend to have a hard time understanding them.

Once you have a pointer to a virtual base, there's no way to convert it back into a pointer to its enclosing class. This means that if you have MCollectible as a virtual base (even indirectly), for example, and stick your object in a collection, there's no way to convert it back to the right type via a cast when you get it out of the collection. This problem doesn't occur with the template versions of the Taligent Collection classes, but watch for it in your own classes. Also, avoid casting base classes to derived classes if at all possible; templates help with that, too.

NOTE Dynamic casts, a new feature of C++, can circumvent this problem, but are an expensive technique. For information about dynamic casts, see "Avoid type casting" on page 67.

Virtual bases are always initialized by the most derived class, whether they are accessible to that class or not. So, if a class TBase has a private virtual base VVirtual, then constructors for class TDerived (which has TBase as a base) must supply the constructor arguments for VVirtual, even though Virtual is not accessible to TDerived. This is a violation of encapsulation, but that's how it works.

NOTE A base class should either always be a virtual base or never be a virtual base; it should almost never be a virtual base of some derived classes and a nonvirtual base of others. This is because there are special (and problematic) constructor semantics for virtual base classes that you must take into account in their design. This is also why virtual base classes have special naming conventions. For more information, see "Name conventions" on page 58.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker