Inheritance and Polymorphism in C++

Lesson 17 of 18 · C++

When several classes share common properties, those properties are moved into a base class, and the other classes inherit it and add their own. With virtual functions the same call works differently for different kinds of objects – this is polymorphism.

Before you start: prior knowledge you need – classes and objects.
How to learn: retype and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are in C++ (C++17); they have been checked to compile and give the output shown.

The base and the derived class

#include <iostream>
#include <string>
using namespace std;

class Animal {                            // base class
protected:                                // visible in derived classes, not from outside
    string name;
public:
    Animal(string n) : name(n) {}
    void introduce() const { cout << "I am " << name << "\n"; }
};

class Dog : public Animal {               // Dog inherits Animal
public:
    Dog(string n) : Animal(n) {}          // calling the base class constructor
    void bark() const { cout << name << ": Woof!\n"; }
};

int main() {
    Dog d("Rex");
    d.introduce();                        // inherited method
    d.bark();                             // its own method
    return 0;
}

The program prints:

I am Rex
Rex: Woof!
AccessIn the classIn a derived classFrom outside
publicyesyesyes
protectedyesyesno
privateyesnono

Virtual functions and polymorphism

#include <bits/stdc++.h>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;              // pure virtual: every shape MUST have it
    virtual string name() const = 0;
    virtual ~Shape() = default;                   // virtual destructor – required with virtual methods
};

class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() const override { return M_PI * r * r; }
    string name() const override { return "circle"; }
};

class Rectangle : public Shape {
    double a, b;
public:
    Rectangle(double a, double b) : a(a), b(b) {}
    double area() const override { return a * b; }
    string name() const override { return "rectangle"; }
};

class Square : public Rectangle {                 // a square is a special rectangle
public:
    Square(double a) : Rectangle(a, a) {}
    string name() const override { return "square"; }
};

int main() {
    int n;
    cin >> n;
    vector<unique_ptr<Shape>> shapes;              // pointers to the base class
    for (int i = 0; i < n; i++) {
        string kind;
        cin >> kind;
        if (kind == "C") { double r; cin >> r; shapes.push_back(make_unique<Circle>(r)); }
        else if (kind == "R") { double a, b; cin >> a >> b; shapes.push_back(make_unique<Rectangle>(a, b)); }
        else { double a; cin >> a; shapes.push_back(make_unique<Square>(a)); }
    }
    double total = 0;
    cout << fixed << setprecision(2);
    for (const auto& s : shapes) {                // the same call, different behaviour
        cout << s->name() << " " << s->area() << "\n";
        total += s->area();
    }
    cout << "total " << total << "\n";
    return 0;
}

For the input below (C = circle, R = rectangle, S = square) the program prints:

3
C 1
R 2 3
S 4
circle 3.14
rectangle 6.00
square 16.00
total 25.14
ConceptMeaning
virtualthe method is chosen by the actual type of the object, not by the type of the pointer
= 0a pure virtual method; a class that has one is abstract – you cannot create an object of it
overridetells the compiler that the method replaces a virtual method from the base class – if the name or the parameters do not match, it reports an error
unique_ptr, make_uniquea smart pointer: the object deletes itself (Pointers)

Without the word virtual the call s->name() would always call the version from the class Shape. Polymorphism makes it possible to add a new kind of shape (e.g. a triangle) without changing the loop in main.

When to use inheritance

RelationshipSolutionExample
"is a kind of" (is-a)inheritanceA square is a rectangle, a dog is an animal
"has" (has-a)an attribute (composition)A car has an engine – Engine engine; inside the class Car

Inheritance is rarely used at competitions; in games, simulations and bigger programs it is used very often. The same concepts in Java: Class inheritance (Java).

Practice tasks

Every task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: medium

Employees and salaries

The base class Employee has a name and the virtual method salary(). Derived classes: Permanent (a fixed monthly salary) and Hourly (number of hours × price per hour). Read n employees (P name salary or H name hours price) and print every name with the salary, and the total cost.

Example

Input

3
P Ana 90000
H Marko 40 1200
P Iva 75000

Output

Ana 90000
Marko 48000
Iva 75000
total 213000
Common mistakes and tips
  • In a base class with virtual methods always write virtual ~MyClass() = default;.
  • Polymorphism works only through pointers or references – vector<Shape> (without pointers) "slices" the objects down to their base part.
  • Write override with every replaced method – then the compiler reports mistakes in the name or the parameters.

Check your knowledge

Open the quiz

Inheritance and polymorphism

1. What is an abstract class?




2. Who can access a protected member?




3. What does the word override do?