Virtual functions

Virtual functions allow the system to decide which functions to execute at run time. Use them to defer abstract-operation implementation to a derived class (best), or to allow a derived class to augment the implementation of an operation defined in the base (not as good).

Do not use virtual functions to trap calls and then take an action based on where the calls came from. Such traps are often used to handle erroneous conditions in the caller. These mechanisms wreak havoc with the data abstractions and ruin one of the major benefits of object-oriented programming. If you override a function, the override must make sense in terms of the definition of the function itself and that of its class.

Virtual functions inherently allow function calls to cascade back through the base classes--for example, DerivedDerived::Foo calls Derived::Foo, which calls Base::Foo. To avoid cascading calls to inherited functions, define an empty hook function. If it is called inside the base class only, make the hook function a private virtual. You can make it protected, but that solves the problem only for the first derived class. Subsequent classes must know whether to call the inherited hook.

[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