Inheritance & Polymorphism
Inheritance creates class hierarchies. Virtual functions enable polymorphism — calling the right method based on the actual object type at runtime. This is fundamental for extensible, maintainable software design.
40 min•By Priygop Team•Last updated: Feb 2026
Inheritance Code
Example
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
// Abstract base class
class Shape {
protected:
string color;
public:
Shape(const string &color) : color(color) {}
virtual ~Shape() = default; // Virtual destructor (essential!)
// Pure virtual function (makes class abstract)
virtual double area() const = 0;
virtual void draw() const = 0;
// Non-virtual: shared implementation
string getColor() const { return color; }
};
class Circle : public Shape {
double radius;
public:
Circle(double r, const string &color = "red")
: Shape(color), radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
void draw() const override {
cout << "Drawing " << color << " circle (r=" << radius << ")" << endl;
}
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h, const string &color = "blue")
: Shape(color), width(w), height(h) {}
double area() const override { return width * height; }
void draw() const override {
cout << "Drawing " << color << " rectangle (" << width << "x" << height << ")" << endl;
}
};
int main() {
// Polymorphism: base pointer holds derived objects
vector<unique_ptr<Shape>> shapes;
shapes.push_back(make_unique<Circle>(5.0));
shapes.push_back(make_unique<Rectangle>(4.0, 6.0));
shapes.push_back(make_unique<Circle>(3.0, "green"));
// Calls correct draw() and area() for each type
for (const auto &shape : shapes) {
shape->draw();
cout << "Area: " << shape->area() << endl;
}
// Shape s; // ERROR: cannot instantiate abstract class
return 0;
}