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

Conditions for dynamic dispatch

Dynamic dispatch occurs only when:

  1. Method is virtual, and.
  2. Object accessed through a pointer or reference.

Notice that dynamic dispatch would be irrelevant anyway when accessing an object by value (i.e., directly, not through a pointer/reference):

class Canine : public Mammal { // ... virtual void bite(Person target); }; class PitBull : public Canine { // ... virtual void bite(Person target); virtual void murdalize(Person target); }; // ... later ... PitBull mauler; Canine pooch = mauler; Canine * fido = &mauler; mauler.bite(intruder); // Dynamic dispatch is irrelevant pooch.bite(me); // for both of these cases fido->bite(me); // But still relevant here.

Caveat: Dynamic dispatching does not mean that you can call methods that are not valid on the type of the pointer. So, for example, you could not call the method murdalize() through a Canine pointer.

Pure virtual functions

It is possible to define a pure virtual member function, which is a function that has no implementation. The syntax is as follows:

class Shape { // ... virtual void draw() = 0; // "Pure" virtual };

A class with a pure virtual function cannot be directly instantiated (what would happen if we tried to call the draw() method on a Shape instance?). A class with a pure virtual function is abstract---it only exists to be subclassed. Subclasses must override the pure virtual function if they are to be instantiated.


Last modified: Wed Jul 26 18:58:45 PDT 2000