Polymorphism
Lesson 15 of 20One call, many behaviours: Animal* pointers, the virtual keyword and the famous zoo loop, animated live.
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.
How virtual dispatch flows
One pointer, two possible targets — the call checks which object is really there.
One loop, two animals
Press play — the same line zoo[i]->speak() prints Woof! first, then Meow!. That is polymorphism.
1#include <iostream>2class Animal {3public:4virtual void speak() { std::cout << "...\n"; }5};6class Dog : public Animal {7public:8void speak() { std::cout << "Woof!\n"; }9};10class Cat : public Animal {11public:12void speak() { std::cout << "Meow!\n"; }13};14int main() {15Dog d;16Cat c;17Animal* zoo[2] = { &d, &c };18for (int i = 0; i < 2; i = i + 1) {19zoo[i]->speak();20}21return 0;22}
The preprocessor pastes in iostream for cout.
Predict the output
An Animal pointer aimed at a Cat — which speak() runs?
1#include <iostream>23class Animal {4public:5virtual void speak() { std::cout << "...\n"; }6};78class Cat : public Animal {9public:10void speak() { std::cout << "Meow!\n"; }11};1213int main() {14Cat c;15Animal* p = &c;16p->speak();17return 0;18}
Hint: The pointer type is Animal*, but the real object is a Cat — virtual dispatch checks the object, not the pointer.
Match the polymorphism terms
Click a term, then click its description to lock the pair.
Key takeaways
virtual on the base method switches on runtime dispatch.
The pointer type is Animal*, but the object’s real type decides what runs.
One loop, one call site, many behaviours — that is polymorphism.
Without virtual, the pointer type alone picks the method.
New child classes plug into old loops with zero changes.