Lesson 14 of 20Object-Oriented C++28 min

Inheritance and Polymorphism

Inheritance lets a derived class reuse and extend a base class. Polymorphism lets one base-class interface call different derived implementations.

Base and Derived Classes

Polymorphism example
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Shape
{
public:
    virtual double area() const = 0;
    virtual ~Shape() = default;
};

class Rectangle : public Shape
{
private:
    double width;
    double height;

public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const override
    {
        return width * height;
    }
};

class Circle : public Shape
{
private:
    double radius;

public:
    explicit Circle(double r) : radius(r) {}

    double area() const override
    {
        return 3.14159 * radius * radius;
    }
};

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

    for (const auto& shape : shapes)
        cout << shape->area() << endl;

    return 0;
}

Important Keywords

KeywordPurpose
publicCreates public inheritance.
virtualEnables runtime polymorphism.
overrideConfirms that a derived method overrides a base method.
= 0Makes a virtual function pure and the base class abstract.
Practice task

Create a base class named Employee and two derived classes that calculate pay differently.

Lesson Summary

Reuse class behaviour and call overridden methods through base-class references.