Runtime Poly (Virtual)
Overview
If you have an array of Animal* pointers, and you throw a Dog and a Cat into it, looping through and calling ->speak() will disastrously just call the generic Animal::speak() function. The compiler only sees the Pointer type (Animal), so it blindly executes the Animal code.
To achieve true Runtime Polymorphism, you must declare the parent's function as `virtual`. The virtual keyword forces the compiler to build a hidden 'vTable' (Virtual Table) in memory. When the program runs, the CPU checks this table dynamically, realizes the pointer is secretly holding a Dog, and executes the Dog's specific, Overridden function instead.
Syntax
#include <iostream>
class Animal {
public:
// 1. VIRTUAL KEYWORD
// Tells the compiler: "Wait until runtime to see what this really is!"
virtual void speak() {
std::cout << "Generic Animal Sound\n";
}
};
class Dog : public Animal {
public:
// 2. OVERRIDE KEYWORD (Optional, but highly recommended for safety)
void speak() override {
std::cout << "Bark!\n";
}
};
int main() {
// A Parent Pointer physically holding a Child Object!
Animal* myPet = new Dog();
// Because of 'virtual', the CPU dynamically routes this to Dog::speak()
myPet->speak(); // Prints "Bark!"
delete myPet;
return 0;
}Common Pitfalls
- Forgetting the
virtualDestructor. If you use polymorphic pointers (Animal* p = new Dog();), and you calldelete p;, the CPU will only execute theAnimaldestructor. TheDogdestructor is ignored, causing massive memory leaks. You MUST declarevirtual ~Animal()in the parent class to fix this.
Interview Questions
override keyword specifically do in C++11, and why is it considered mandatory in modern engineering?The override keyword does not change how the code runs. It is a strict directive to the Compiler. It verifies that you are actually overriding a valid virtual function from the Parent. If you misspell the function name (e.g., speek()), the compiler will instantly throw a fatal error instead of silently creating a brand new function.
Real-World Example
Using polymorphic arrays to process hundreds of different game entities using a single loop.
#include <iostream>
#include <vector>
class Entity {
public:
virtual void update() { std::cout << "Entity updated.\n"; }
};
class Player : public Entity {
public:
void update() override { std::cout << "Player physics applied.\n"; }
};
class Bomb : public Entity {
public:
void update() override { std::cout << "Bomb tick down!\n"; }
};
int main() {
// Array of Parent Pointers!
std::vector<Entity*> world;
world.push_back(new Player());
world.push_back(new Bomb());
// The CPU dynamically figures out what each object is at runtime!
for (Entity* e : world) {
e->update();
}
return 0;
}Check Your Knowledge
Test your understanding of Runtime Poly (Virtual) with these quick questions.