[   ^ to index...   |   next -->   ]

CSE 143/AE : 27 July 2000


Inheritance and method dispatch

Organizing classes into inheritance heirarchies naturally leads us to reformulate our rules for how methods are called. Why? Consider the situation:

class Point { // ... some stuff, then: public: void draw(); // simply draws a point }; class ColoredPoint { // ... some stuff, then: public: void draw(); // will set pen color, then draw }; Point * my_cpoint = new ColoredPoint( 0, 0, COLOR_RED ); my_cpoint->draw();

The object to which my_point points is in fact a ColoredPoint instance. When we draw this object, we would really prefer that it draw itself as a ColoredPoint, even though we only have a Point pointer to it.

However, under our current rules of method lookup, the call to draw() above would result in a call to the Point class's definition of draw(), because the static type of the pointer is Point. This convention is called static dispatch, because we "dispatch" the method call based on the static type of the pointer.

We need a new concept---a way to have the language look up the dynamic type of the object to which a pointer or reference refers, and then call the appropriate method.

In fact, this feature is crucial to making an object-oriented language work, and it is called dynamic dispatch.


Last modified: Wed Jul 26 18:51:40 PDT 2000