0Pricing
C++ Academy · Lesson

Static Polymorphism

Avoid virtual call overhead.

Two Kinds of Polymorphism

C++ supports two flavors of polymorphism.

  • Dynamic: virtual functions resolved at runtime via vtable
  • Static: templates/CRTP resolved at compile time

Static polymorphism trades flexibility for speed.

The Cost of virtual

A virtual call requires an indirect jump through the vtable. The compiler usually cannot inline it, blocking many optimizations.

#include <iostream>

struct Shape {
    virtual double area() const = 0;
    virtual ~Shape() = default;
};

struct Square : Shape {
    double s;
    Square(double x) : s(x) {}
    double area() const override { return s * s; }
};

int main() {
    Shape* p = new Square(3);
    std::cout << p->area() << "\n";
    delete p;
    return 0;
}

All lessons in this course

  1. The CRTP Idiom
  2. Static Polymorphism
  3. Mixins with CRTP
  4. When to Use CRTP
← Back to C++ Academy