⚡C++IntermediateLesson 28 of 50CamboFreelanceJune 19, 2026
C++ Polymorphism
Understand C++ polymorphism with virtual functions and override. Learn runtime dispatch, base class pointers, and practical OOP design.
Intermediate9 min readLesson 28 of 50
What is Polymorphism?
Polymorphism means "many forms". A single interface (base class pointer) can call different implementations depending on the actual object type at runtime.
Virtual Functions
Declare a method virtual in the base class to enable runtime polymorphism:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle" << endl;
}
};
class Triangle : public Shape {
public:
void draw() override {
cout << "Drawing a Triangle" << endl;
}
};
int main() {
Shape* shapes[3];
shapes[0] = new Shape();
shapes[1] = new Circle();
shapes[2] = new Triangle();
for (int i = 0; i < 3; i++) {
shapes[i]->draw(); // correct method called for each type
}
// cleanup
for (int i = 0; i < 3; i++) delete shapes[i];
return 0;
}
Output:
Drawing a shape
Drawing a Circle
Drawing a Triangle
override keyword: Always use override on derived class methods. It tells the compiler to verify that you are indeed overriding a virtual function — catching typos and signature mismatches at compile time.
Exercise
Create a Animal base class with virtual speak(). Derive Dog, Cat, Bird — each with their own speak(). Store all three in an array of base pointers and call speak() on each.
Show Solution
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() { cout << "..." << endl; }
virtual ~Animal() { }
};
class Dog : public Animal { public: void speak() override { cout << "Woof!" << endl; } };
class Cat : public Animal { public: void speak() override { cout << "Meow!" << endl; } };
class Bird : public Animal { public: void speak() override { cout << "Tweet!" << endl; } };
int main() {
Animal* animals[] = { new Dog(), new Cat(), new Bird() };
for (Animal* a : animals) { a->speak(); delete a; }
return 0;
}
Quiz
What keyword enables runtime polymorphism in C++?
A) abstract
B) virtual
C> override
D) poly
Answer
B) virtual — declaring a method virtual in the base class enables runtime dispatch.
Summary
Polymorphism allows different objects to respond to the same interface differently.
Use virtual in the base class and override in derived classes.
Base class pointers/references can hold derived objects.
Add a virtual destructor to base classes when using polymorphism.