next up previous contents
Next: Hardware Description Using C++ Up: Features of Object-Oriented Programming Previous: Inheritance

Dynamic Binding of Function Calls

Quite often when using inheritance, one will discover that a series of classes share a common behaviour, but how that behaviour is implemented is different from class to class. Such a situation is a prime candidate for the use of dynamic or runtime binding which is also referred to as polymorphism.

Going back to our previous example, we may decide to derive two tree classes from our graph class, the first class, in_order_tree would be traversed in an ``in order'' fashion when it received a traverse() message, whereas post_order_tree would be traversed in a ``post order'' manner. The different traversal algorithms could be incorporated into a dynamically bound traverse() method. Now, when one of these trees is passed to a function which accepts a reference to a graph class, the invocation of the traverse() method via the graph parameter would call the correct traversal algorithm at runtime depending upon which tree was passed to the function. This reduces the burden on the programmer since a tag does not have to be associated with each class derived from graph to distinguish it from other graphs. In addition, the programmer would not have to maintain an unwieldy switch statement to determine which traversal algorithm to invoke since this is all handled automatically by the compiler.

C++ implements dynamic binding through the use of virtual functions. While function calls resolved at runtime are somewhat less efficient than function calls resolved statically, Stroustrup [18] notes that a typical virtual function invocation requires just five more memory accesses than a static function invocation. This is a very small penalty to pay for a mechanism which provides significant flexibility for the programmer, as will be shown later.

It is from inheritance and runtime binding of function calls that object-oriented programming languages derive most of their power. Some problems lend themselves very well to these two concepts, while others do not. As Stroustrup notes:

``How much types have in common so that the commonality can be exploited using inheritance and virtual functions is the litmus test of the applicability of object-oriented programming.''

As will be shown in the next two chapters, the object-oriented paradigm can be very easily applied to the problem of hardware description and simulation.


next up previous contents
Next: Hardware Description Using C++ Up: Features of Object-Oriented Programming Previous: Inheritance

Donald Craig
Sat Jul 13 16:02:11 NDT 1996