Polymorphism

Lesson 15 of 20

One call, many behaviours: Animal* pointers, the virtual keyword and the famous zoo loop, animated live.

The big picture

One call, many forms

Poly = many, morph = form. The same line of code behaves differently for different objects.

The virtual keyword

Mark a method virtual in the base class to switch on runtime dispatch for it.

Override

A child class replaces the inherited version with its own — Dog rewrites speak().

Base pointers

An Animal* may point at a Dog or a Cat — any child fits behind one pointer type.

The object decides

At call time C++ checks what the pointer really aims at, then runs that version.