Study Guide · 09
Polymorphism
One interface, many implementations — chosen at runtime with virtual
1
Notes
2
Videos by Dr. Ibrahim Albluwi
3
Code examples
4
Lab walkthroughs
Key Concepts
This page is a short summary. The full notes are in Polymorphism.pdf on Google Drive.
Summary
01 · What is polymorphism?
02 · Static vs dynamic binding
- Without
virtual,s->draw()follows the pointer type and prints "Drawing a shape" — static binding, decided at compile time. - With
virtual void draw()in the base andvoid draw() overridein the derived class, the real object decides at runtime — dynamic (late) binding. - Calling through an object name (
c.draw();) is always compile-time; only pointers and references are polymorphic.
03 · The four rules
04 · Abstract classes
05 · Virtual destructors
06 · Arrays of base pointers
Shape* shapes[3];can hold a Circle, a Rectangle and a Triangle;shapes[i]->draw();calls each one's own version.- Free them with
delete shapes[i];in a loop — this is why the destructor must be virtual. - This replaces error-prone
switchstatements on type: each class handles its own behaviour, so adding a shape is easy.
Extra Notes · beyond the PDF
Good to know
virtualis only needed in the base class — overrides stay virtual automatically (still writeoverride).- Polymorphism only works through pointers or references. Copying a derived object into a base object slices off the derived part (object slicing).
- An abstract class can still have data members, constructors and normal functions.
Common mistakes
- Forgetting
virtualin the base — calls go to the base version (static binding). - A different signature (a missing
const, another parameter type) makes a new function instead of an override —overridecatches it. - No virtual destructor in a base class used through pointers — the derived destructor never runs.
- Trying to create an object of an abstract class.