Polymorphism
Overview
The word Polymorphism comes from Greek, meaning 'Many Forms'. In C++, it is the ability for a single function name, or a single Object Pointer, to behave completely differently depending on the context in which it is used.
Without polymorphism, a game engine would need a drawPlayer(), drawEnemy(), and drawTree() function. With polymorphism, you simply create an array of generic Entity pointers, throw every object into it, and loop through calling ->draw(). The compiler dynamically figures out what 'form' the object currently is and executes the correct, specific code for it.
Syntax
// Polymorphism is split into two primary architectures in C++:
//
// 1. COMPILE-TIME (Static) Polymorphism
// - Function Overloading (Functions with the same name, different parameters)
// - Operator Overloading (Changing what '+', '-', '==' do for custom classes)
// - Happens incredibly fast because the compiler resolves it BEFORE the program runs.
//
// 2. RUNTIME (Dynamic) Polymorphism
// - Function Overriding (Virtual Functions)
// - The CPU decides which function to execute dynamically WHILE the program is running.Common Pitfalls
- Assuming all inheritance automatically provides Polymorphism. Just because a
Doginherits fromAnimal, callinganimalPtr->speak()will always trigger theAnimal's generic speak function, NOT the Dog's bark. You must explicitly opt-in to polymorphism using thevirtualkeyword.
Interview Questions
Runtime Polymorphism fundamentally requires the CPU to perform a 'vTable Lookup' (Virtual Table). Every time you call a virtual function, the CPU must jump to a hidden array in memory, look up the correct memory address for the specific function, and then jump to it. This indirection costs CPU cycles and breaks CPU caching.
Real-World Example
A conceptual view of why Polymorphism makes code scalable.
/*
Instead of writing this:
player.update();
enemy1.update();
enemy2.update();
boss.update();
Polymorphism allows this:
for(Entity* e : gameWorld) {
e->update(); // Dynamically executes the correct specific logic!
}
*/Check Your Knowledge
Test your understanding of Polymorphism with these quick questions.