Advanced OOP: Inheritance and Polymorphism
8 min read
Welcome back! 🚀 If you are reading this, you’ve likely mastered classes, objects, and encapsulation. You know how to build a blueprint (Class) and build a house (Object).
Now, imagine you have to build an entire city. You have Houses, Skyscrapers, Banks, and Libraries. They are all "Buildings". They all have walls and doors. Do you copy-paste the code for "Wall" and "Door" into every single class?
Absolutely not. That is a violation of the DRY (Don't Repeat Yourself) principle. If you fix a bug in the "Door" code, you don't want to hunt it down in 50 different files.
Today, we dive into the hierarchy of C++. We are going to learn how to organize code relationships (Inheritance) and how to make code behave intelligently based on what it actually is (Polymorphism).
1. Inheritance: Reusing and Extending Code
The Problem: Code Duplication
Imagine we are building a generic RPG game. We have a Knight and a Wizard.
class Knight {
public:
int health;
void walk() { /* logic to move x, y */ }
void slash() { /* sword logic */ }
};
class Wizard {
public:
int health;
void walk() { /* logic to move x, y */ } // <--- DUPLICATE CODE
void castSpell() { /* magic logic */ }
};Both classes have health and walk(). In a real production codebase, walk() might be 200 lines of collision detection physics. Copy-pasting that is a crime against humanity.
The Concept: Inheritance
Inheritance is the mechanism by which one class acquires the properties (member variables) and behaviors (member functions) of another class.
- Base Class (Parent): The generic class containing shared logic (e.g.,
Player). - Derived Class (Child): The specific class that inherits from the Base (e.g.,
Knight).
The Solution
We create a Player class and have others inherit from it.
#include <iostream>
#include <string>
// The Base Class
class Player {
public:
int health = 100;
std::string name;
void walk() {
std::cout << name << " is walking forward.\n";
}
};
// The Derived Class
// syntax: class Derived : access_specifier Base
class Knight : public Player {
public:
void slash() {
std::cout << name << " swings a sword! ⚔️\n";
}
};
class Wizard : public Player {
public:
void castSpell() {
std::cout << name << " casts a fireball! 🔥\n";
}
};
int main() {
Knight k;
k.name = "Arthur"; // Inherited property
k.walk(); // Inherited method
k.slash(); // Unique method
return 0;
}🧠 Industry Standard & Practical Notes
publicInheritance: You noticed: public Player. This is used 99% of the time. It means "A Knight IS A Player".- Access Specifiers:
public: Everyone can access.private: Only the class itself can access (Derived classes cannot access private members of the Base).protected: The class and its children (Derived classes) can access, but outsiders cannot.
- Constructors: When you create a
Knight, C++ first builds thePlayer(Base), then adds theKnightfeatures on top. When destroyed, it happens in reverse (Knight first, then Player).
2. Method Overriding and Virtual Functions
The Problem: The Pointer Trap
Here is where C++ gets tricky. In professional software, we rarely hold objects directly (like Knight k). We usually hold pointers to objects, often storing them in a list of Player*.
Look at this scenario:
Player* myPlayer = new Knight(); // Valid! A Knight IS A Player.
myPlayer->walk(); // Works fine.But what if the Knight walks differently? What if Knights move slower because of armor?
class Player {
public:
void walk() { std::cout << "Player walks normally.\n"; }
};
class Knight : public Player {
public:
// We want to override this
void walk() { std::cout << "Knight walks slowly (Clank Clank).\n"; }
};
int main() {
Player* p = new Knight();
p->walk(); // OUTPUT: "Player walks normally." <--- WRONG! 😱
}Why? This is called Static Binding. The compiler sees p is a Player* pointer. It decides at compile time to call Player::walk(), ignoring the fact that the object is actually a Knight.
The Concept: Virtual Functions
To fix this, we need Dynamic Binding. We tell the compiler: "Don't decide now. Check the object type while the program is running."
We do this using the keyword virtual.
The Solution
class Player {
public:
// 'virtual' tells the compiler to look up the actual object type at runtime
virtual void walk() {
std::cout << "Player walks normally.\n";
}
};
class Knight : public Player {
public:
// 'override' is a safety keyword (C++11).
// It ensures you are actually overriding a base function and didn't make a typo.
void walk() override {
std::cout << "Knight walks slowly (Clank Clank).\n";
}
};
int main() {
Player* p = new Knight();
p->walk(); // OUTPUT: "Knight walks slowly (Clank Clank)." ✅
}🕵️ Under The Hood: The V-Table
This is a favorite interview question. How does virtual work?
When a class has a virtual function, the compiler secretly adds a pointer member to the class called a vptr. This points to a V-Table (Virtual Table).
- The V-Table is a lookup array of function pointers.
- When you call
p->walk(), the program follows thevptrto the table, finds the correct address forKnight::walk, and jumps there. - Performance Note: This adds a tiny bit of overhead (a few nanoseconds), but it makes flexible architecture possible.
3. Polymorphism: One Interface, Many Implementations
The Definition
Polymorphism comes from Greek: Poly (many) + Morph (forms). It allows code to interact with objects of different types through a uniform interface.
The Problem: The "Switch Case" Nightmare
Without polymorphism, if you have a list of game entities, you have to write this garbage:
// DON'T DO THIS
if (type == KNIGHT) { ((Knight*)obj)->slash(); }
else if (type == WIZARD) { ((Wizard*)obj)->castSpell(); }
else if (type == DRAGON) { ((Dragon*)obj)->fire(); }This is hard to maintain. If you add a Thief class, you have to edit every if/else chain in your entire codebase.
The Solution: Polymorphism in Action
We treat every specific class as the Base class.
#include <vector>
class Player {
public:
virtual void specialMove() {
std::cout << "Player does nothing special.\n";
}
// VITAL: Virtual Destructor (explained in next section)
virtual ~Player() {}
};
class Knight : public Player {
public:
void specialMove() override { std::cout << "⚔️ Sword Slash!\n"; }
};
class Wizard : public Player {
public:
void specialMove() override { std::cout << "🔥 Fireball!\n"; }
};
int main() {
// A list of pointers to the Base class
std::vector<Player*> party;
party.push_back(new Knight());
party.push_back(new Wizard());
party.push_back(new Knight());
// ONE LOOP to rule them all
for (Player* p : party) {
p->specialMove();
// 1st iteration: Sword Slash
// 2nd iteration: Fireball
// 3rd iteration: Sword Slash
}
// Cleanup
for (Player* p : party) delete p;
}💡 Industry Practice
In modern C++ (C++11 and later), we rarely use raw pointers (new/delete) like above because memory leaks are scary.
We use Smart Pointers.
std::vector<std::unique_ptr<Player>> party;
party.push_back(std::make_unique<Knight>());
// No 'delete' needed! It cleans itself up.4. Abstract Classes and Pure Virtual Functions
The Problem: The "Generic" Object
In the examples above, we could do this:Player* p = new Player();
But what is a generic "Player"? Does it have a weapon? What does it look like? In many systems, the Base class is just a concept (an Interface) and should never be instantiated directly.
The Concept: Pure Virtual Functions
A Pure Virtual Function is a function that has no implementation in the Base class. We set it to equal zero.virtual void attack() = 0;
If a class contains at least one pure virtual function, it becomes an Abstract Class. You cannot create an object of an Abstract Class.
The Solution
// Abstract Class (Interface)
class GameEntity {
public:
// Use this to enforce a contract.
// "Every GameEntity MUST implement a draw function."
virtual void draw() = 0;
// Virtual Destructor is MANDATORY for base classes!
virtual ~GameEntity() {
std::cout << "Entity destroyed.\n";
}
};
class Goblin : public GameEntity {
public:
// We MUST implement draw(), or Goblin becomes abstract too.
void draw() override {
std::cout << "Drawing a green Goblin.\n";
}
};
int main() {
// GameEntity e; // ❌ ERROR: Cannot instantiate abstract class
GameEntity* e = new Goblin(); // ✅ Allowed
e->draw();
delete e;
}🚨 Critical Industry Warning: Virtual Destructors
Did you notice virtual ~GameEntity()?
If you delete a Derived object through a Base pointer, and the Base destructor is NOT virtual, the Derived destructor will NOT be called.
- Result: Memory leak. The
Goblinpart of the memory is never cleaned up. - Rule: If a class is meant to be inherited from, give it a
virtualdestructor.
Summary for the Pro
- Inheritance (
: public Base): Allows code reuse. Model "Is-A" relationships. - Virtual Functions: Enable Dynamic Binding. Allows the correct method to be called at runtime based on the actual object type.
override: Always use this keyword in derived classes to prevent bugs.- Polymorphism: Store different derived objects in a single container (e.g.,
vector<Base*>) and treat them uniformly. - Abstract Classes (
= 0): Define interfaces/contracts. Cannot be instantiated. - Virtual Destructor: Mandatory for base classes to prevent memory leaks.
📚 References & Further Reading
Challenge
Challenge: Polymorphic UI Rendering Engine
You are tasked with creating a rudimentary UI rendering system for a game engine. The system must handle various types of UI elements, but you want to manage and render them through a single, unified interface using polymorphism.
Your tasks are:
- Define an abstract base class named
UIComponent. This class must serve as an interface and should not be instantiable. - The
UIComponentclass must declare a pure virtual functionrender()which takes no arguments and returnsvoid. - Ensure that
UIComponenthas a virtual destructor to guarantee proper memory cleanup when derived objects are deleted through a base class pointer. - Implement three concrete classes that publicly inherit from
UIComponent:Button: This class should have a privatestd::stringmember to store itslabel. Its constructor should initialize this label. The overriddenrender()method should printRendering Button: [label]to the console.Image: This class should have a privatestd::stringmember for itsimagePath. Its constructor should initialize this path. The overriddenrender()method should printRendering Image from: [imagePath].TextBox: This class should have a privatestd::stringmember for itscontent. Its constructor should initialize this content. The overriddenrender()method should printRendering TextBox with content: [content].
- In the
mainfunction, create astd::vectorthat can holdstd::unique_ptrs toUIComponentobjects. - Populate this vector with at least one instance of each concrete class (
Button,Image,TextBox). You must usestd::make_uniqueto create the objects and manage their memory. - Finally, iterate through the vector and call the
render()method on each element. This will demonstrate polymorphism, as the correctrenderfunction will be called for each object at runtime.
Expected result
The program should compile without errors. When executed, it must print one line for each UI component that was added to the vector. The output demonstrates that the correct render() method was called for each object type.
For example, if you created a Button with label "Login", an Image with path "/img/avatar.png", and a TextBox with content "Welcome!", the output should be:
Rendering Button: Login
Rendering Image from: /img/avatar.png
Rendering TextBox with content: Welcome!The order of the lines in the output depends on the order in which the objects were added to the vector.