C++C++ Explainer
C++ · 2 · Classes & RAII7 / 36 · 19%

Inheritance & Polymorphism

virtual functions enable runtime dispatch through a vtable.

shortcuts: ← prev · → next · M mark
1

virtual

Override in derived classes and call through a base pointer/reference.

Example
example
struct Shape {
    virtual double area() const = 0;   // pure virtual
    virtual ~Shape() = default;
};
struct Circle : Shape {
    double r;
    Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
};
Dog objvptr →Dog vtablespeak → Dog::speak~Dog → ~Dog()virtual call → indirect through vptr
vtable dispatch
2

override & final

Ask the compiler to check you actually override.

Example
example
struct D : Shape {
    double area() const override { return 0; }
    // typo like: double are() const override;  → compiler error
};
3

Virtual Destructor

Base with virtual functions must have virtual dtor, or deletion is UB.

Example
example
Shape* s = new Circle(2);
delete s;   // needs Shape::~Shape() virtual