← C++ roadmap

Topic 6 of 27 · Intermediate

Inheritance & Virtual Functions

Runtime polymorphism, vtables, abstract classes and override.

Concept

A derived class inherits from a base. Marking a function virtual lets calls through a base pointer/reference dispatch to the derived version at run time.

Each polymorphic class has a vtable of function pointers; each object stores a hidden vptr to it.

A pure virtual function (= 0) makes a class abstract. Base classes used polymorphically must have a virtual destructor.

Code (C++20)

#include <iostream>
#include <memory>
#include <vector>

struct Shape {
    virtual double area() const = 0;
    virtual ~Shape() = default;      // essential
};
struct Circle : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
};
struct Rect : Shape {
    double w, h;
    Rect(double w, double h) : w(w), h(h) {}
    double area() const override { return w * h; }
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1));
    shapes.push_back(std::make_unique<Rect>(2, 3));
    for (auto& s : shapes) std::cout << s->area() << '\n';
}

Remember

  • Virtual destructor in polymorphic bases.
  • Use override and final.
  • Passing by value slices derived objects.

Interview questions

How do virtual functions work?

The compiler builds a vtable per class; each object holds a vptr. A virtual call looks up the function in the vtable at run time.

What is object slicing?

Copying a derived object into a base object by value drops the derived part. Use references or pointers.

Practise C++ with the AI mentor

Lesson test

Take an 8-question test on “Inheritance & Virtual Functions” — concepts, output prediction, bug spotting and interview questions.

Can't find a C++ topic you need for exams or placements? Request it and we'll add it.