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

Dynamic dispatch: virtual methods

In the following code example, the method draw() is declared virtual. Whenever draw() is called through a Point pointer or reference, C++ will look up the actual dynamic, runtime type of the corresponding object and execute the proper version of the method.

class Point { // ... some stuff, then: public: virtual void draw(); // notice virtual declaration }; class ColoredPoint : public Point { // ... some stuff, then: public: virtual void draw(); // virtual redeclared for documentation }; class BlinkingPoint : public Point { // ... some stuff, then: public: virtual void draw(); }; Point * my_cpoint = new ColoredPoint( 0, 0, COLOR_RED ); Point * my_bpoint = new BlinkingPoint( 0, 0, true ); my_cpoint->draw(); my_bpoint->draw();

Conceptually, you can imagine that for each virtual method, the runtime object has a "pointer" to the proper method to execute for that object.


Last modified: Thu Jul 27 13:18:49 PDT 2000