Decide now what might be overridden later

Because the calling site for a function must execute different code depending on whether it is virtual or not, it is not possible to change a function from virtual to nonvirtual, or vice versa, without breaking binary compatibility. Therefore, any class that might allow polymorphism in the future should use virtual functions now, and any function that will eventually allow overriding should be virtual now. This is true even if derived classes and overriding are not allowed now. Because this is an irrevocable decision, it's better to pay the few extra cycles and reserve the option to allow derived classes later. (Virtual function calls in the Taligent Runtime system have very low overhead relative to regular function calls.)

Remember, making something virtual does not mean it can be overridden; whether and how member functions can be overridden must be stated in the class definition.

Of course, if you are sure that you will never have derived classes, or that a given function should never be overridden, you don't need to make your functions virtual. You can find examples in the Taligent Application Environment, including TGPoint, TToken, and the complex class. And if your class can afford an extra function call, you can add a virtual version later and have the nonvirtual version call it.

NOTE Inline functions can be virtual. When the compiler knows the type of the object at compile time, it generates the inline; when it does not (such as when a pointer or reference is used), it calls the function through a virtual dispatch. See "Virtual inline functions where the type is not known" on page 93 for more on this.


[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