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:
- Method is virtual, and.
- Object accessed through a pointer or reference.
Caveats:
- 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.
- Dynamic dispatch only occurs on the object on which the method is invoked. We cannot dynamically dispatch based on any of the method's arguments.