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

More details of inheritance

Static vs. dynamic dispatch

Consider the following extensions (assume everything's public):

class Canine : public Mammal { // ... void bite(Person target); }; class PitBull : public Canine { // ... void bite(Person target); void murdalize(Person target); }; // ... later ... PitBull * mauler = new PitBull(); Canine * pooch = mauler; mauler->bite(intruder); pooch->bite(me);

Under static dispatch, the method is dispatched based on the static type of the object. So the good news is, pooch did not bite(me) as a PitBull, but as a regular Canine. However, if we substituted each bite() method above with:

virtual void bite(Person target);

Then we would get dynamic dispatch, and the code above would result in a PitBull bite.

Dynamic dispatch occurs when:

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

Caveats:


Last modified: Mon Jul 17 23:09:19 PDT 2000