LearnFrenzy
Sign in Take a free test

Object-Oriented Programming · Lesson 11 of 33

Inheritance and Polymorphism in C++

5 min read Updated Nov 7, 2026 Saurabh Samir

Inheritance lets a class build on another: a SavingsAccount is an Account with interest. Polymorphism lets you treat different derived objects through the same base interface and still get each one's own behaviour. Together they're the classic OOP pillars – and favourite interview topics (virtual functions, vtables, virtual destructors).

In this lesson

  • Base and derived classes
  • virtual functions, override and final
  • Abstract classes and interfaces
  • Virtual destructors and how dispatch works

Base and derived classes

#include <iostream>
#include <string>

class Employee {
public:
    Employee(std::string name, double salary) : salary_(salary), name_(std::move(name)) {}   // declaration order
    const std::string& name() const { return name_; }
    double salary() const { return salary_; }
protected:                                   // visible to derived classes, not to outsiders
    double salary_;
private:
    std::string name_;
};

class Manager : public Employee {            // a Manager is an Employee
public:
    Manager(std::string name, double salary, int reports)
        : Employee(std::move(name), salary), reports_(reports) {}   // construct the base first
    int reports() const { return reports_; }
    void give_raise(double pct) { salary_ *= 1 + pct / 100; }       // uses the protected member
private:
    int reports_;
};

int main() {
    Manager m("Kiran", 150000, 4);
    m.give_raise(10);
    std::cout << m.name() << " manages " << m.reports() << " and earns " << m.salary() << '\n';
    return 0;
}

Output

Kiran manages 4 and earns 165000
AccessInside the classDerived classesOutside code
publicyesyesyes
protectedyesyesno
privateyesnono

virtual functions and polymorphism

#include <iostream>
#include <memory>
#include <numbers>
#include <string>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;                     // virtual destructor: essential for base classes
    virtual double area() const = 0;                // pure virtual: must be overridden
    virtual std::string name() const { return "shape"; }
};

class Circle : public Shape {
public:
    explicit Circle(double r) : r_(r) {}
    double area() const override { return std::numbers::pi * r_ * r_; }
    std::string name() const override { return "circle"; }
private:
    double r_;
};

class Rectangle : public Shape {
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    double area() const override { return w_ * h_; }
    std::string name() const override { return "rectangle"; }
private:
    double w_, h_;
};

class Square final : public Rectangle {             // final: no further derivation
public:
    explicit Square(double s) : Rectangle(s, s) {}
    std::string name() const override { return "square"; }
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1.0));
    shapes.push_back(std::make_unique<Rectangle>(3, 4));
    shapes.push_back(std::make_unique<Square>(5));

    double total = 0;
    for (const auto& s : shapes) {                  // one loop, each shape's own area()
        std::cout << s->name() << ": " << s->area() << '\n';
        total += s->area();
    }
    std::cout << "total area: " << total << '\n';
    return 0;
}

Output

circle: 3.14159
rectangle: 12
square: 25
total area: 40.1416

How s->area() finds the right function

  1. Each class with virtual functions has a vtablea table of pointers to its versions of those functions
  2. Each object stores a hidden vptrpointing to its class's vtable
  3. A virtual call goes through the vptrso a Circle in a Shape pointer runs Circle::area
  4. Costone extra pointer per object and one indirect call – usually negligible
  • virtual enables dynamic dispatch through base pointers and references.
  • override asks the compiler to check that you really override something – a typo in the name or signature becomes an error instead of a silent new function.
  • = 0 makes a function pure virtual and the class abstract: you can't create a Shape directly.

Virtual destructors and slicing

  • If a base class is used polymorphically, give it a virtual destructor. Deleting a derived object through a base pointer without one is undefined behaviour (the derived part isn't destroyed).
  • Copying a derived object into a base value (Shape s = circle;) "slices" off the derived part. Use pointers or references for polymorphism.

Composition over inheritance

Use inheritance for a genuine "is-a" relationship where you need polymorphism. For "has-a" relationships, store a member instead: a Car has an Engine, it isn't one. Composition keeps classes smaller, decoupled and easier to test.

Practice

Try it yourself

  1. Create an abstract Notifier with a pure virtual send(msg), and EmailNotifier and SmsNotifier that print differently; call both through a vector of base pointers.

    Show solution
    #include <iostream>
    #include <memory>
    #include <string>
    #include <vector>
    
    class Notifier {
    public:
        virtual ~Notifier() = default;
        virtual void send(const std::string& msg) const = 0;
    };
    class EmailNotifier : public Notifier {
    public:
        void send(const std::string& msg) const override { std::cout << "[email] " << msg << '\n'; }
    };
    class SmsNotifier : public Notifier {
    public:
        void send(const std::string& msg) const override { std::cout << "[sms] " << msg.substr(0, 10) << "...\n"; }
    };
    
    int main() {
        std::vector<std::unique_ptr<Notifier>> channels;
        channels.push_back(std::make_unique<EmailNotifier>());
        channels.push_back(std::make_unique<SmsNotifier>());
        for (const auto& c : channels) c->send("Your order has shipped");
        return 0;
    }

    Output

    [email] Your order has shipped
    [sms] Your order...

Quick check

What makes a class abstract?

At least one pure virtual function (= 0).

Why use override?

The compiler checks the function really overrides a base virtual function.

Why does a polymorphic base class need a virtual destructor?

So deleting a derived object through a base pointer runs the derived destructor too.

Summary

  • Derived classes extend a base; protected members are visible to them.
  • virtual + override give runtime polymorphism through base pointers/references (via vtables).
  • Abstract classes define interfaces; always give polymorphic bases a virtual destructor.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links