Unit 4: Object-Oriented Programming (OOP) in C++Lesson #14 / 20

Lesson 14: Inheritance, Virtual Functions & Dynamic Polymorphism

NSNextSemLast Updated: 5 Aug, 2026

🧬 Inheritance & Runtime Polymorphism

Inheritance allows child classes to derive properties from a base class. Polymorphism allows treating derived objects through base class pointers using Virtual Functions (virtual).


🛠️ Virtual Tables (vtable) & Dynamic Binding

When a function is declared virtual, C++ creates a hidden VTable (Virtual Table) holding function pointers. Calling ptr->speak() resolves dynamically at runtime based on the actual object instance!


💻 Code Example: Polymorphic Game Entity Architecture

C++ Source Code (main.cpp)
#include <iostream>
#include <vector>
class Enemy {
public:
virtual void attack() const {
std::cout << "Enemy performs generic attack!" << std::endl;
}
virtual ~Enemy() {} // Always make base class destructors virtual!
};
class Dragon : public Enemy {
public:
void attack() const override {
std::cout << "🔥 Dragon breathes FIRE damage!" << std::endl;
}
};
class Robot : public Enemy {
public:
void attack() const override {
std::cout << "🤖 Robot fires LASER beam!" << std::endl;
}
};
int main() {
std::vector<Enemy*> battlefield;
battlefield.push_back(new Dragon());
battlefield.push_back(new Robot());
for (Enemy* unit : battlefield) {
unit->attack(); // Dynamic Polymorphic Call!
delete unit;
}
return 0;
}
Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

(c) Microsoft Corporation. All rights reserved.

C:\Users\Student\CPP_Project>#include <iostream>

C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

Interactive Knowledge Check

Test your understanding of Lesson #14 concepts

What keyword is required in a Base Class function declaration to enable runtime dynamic polymorphism & overriding?