C++ Tutorial · Object-Oriented C++ · Lesson 13 of 21

C++ Inheritance and Polymorphism

Base classes, virtual functions, override and abstract classes.

Virtual functions

Mark a base-class function virtual to allow derived classes to override it, and use override in the derived class so the compiler checks you. Calls through a base pointer or reference use the actual object's version:

Example 1
#include <format>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;          // pure virtual
    virtual std::string name() const { return "Shape"; }
};

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

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

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1.0));
    shapes.push_back(std::make_unique<Rect>(2.0, 3.0));
    for (const auto& s : shapes)
        std::cout << s->name() << " area " << std::format("{:.2f}", s->area()) << '\n';
}

Output

Circle area 3.14
Rect area 6.00

Run this on your computer — see “Get Started” for setup.

  • A pure virtual function (= 0) makes the class abstract.
  • A base class used polymorphically needs a virtual destructor.

Test yourself

Which keyword asks the compiler to verify you're overriding a virtual function?

  1. virtual
  2. override
  3. final
  4. base
Show answer

Answer: override