Skip to main content

Lesson 2 of 6

Virtual Functions & vtable Mechanics

A **virtual function** enables **runtime polymorphism** - the correct function version is called based on the actual object type, not the pointer/reference type. Internally, the compiler adds a **vptr** (virtual pointer) to each object with virtual functions, pointing to the class's **vtable** (virtual dispatch table) - an array of function pointers. `override` (C++11) tells the compiler you intend to override a virtual function - it catches typos in the function signature.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Virtual Dispatch, override/final & vtable Layout

Virtual Dispatch, override/final & vtable Layout
#include <iostream>
#include <vector>
#include <memory>
#include <cmath>

class Shape {
public:
    virtual ~Shape() = default;

    // Pure virtual - forces subclasses to implement
    virtual double area()      const = 0;
    virtual double perimeter() const = 0;
    virtual void   draw()      const = 0;

    // Non-virtual - same for all shapes (uses virtual area/perimeter)
    void describe() const {
        std::cout << "Area: " << area()
                  << "  Perimeter: " << perimeter() << "
";
    }
};

class Circle : public Shape {
    double radius_;
    static constexpr double PI = 3.14159265358979;
public:
    explicit Circle(double r) : radius_(r) {}

    double area()      const override { return PI * radius_ * radius_; }
    double perimeter() const override { return 2 * PI * radius_; }
    void   draw()      const override {
        std::cout << "Drawing Circle(r=" << radius_ << ")
";
    }
};

class Rectangle : public Shape {
    double w_, h_;
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}

    double area()      const override { return w_ * h_; }
    double perimeter() const override { return 2*(w_ + h_); }
    void   draw()      const override {
        std::cout << "Drawing Rectangle(" << w_ << "x" << h_ << ")
";
    }
};

// final - prevents further overriding (or inheritance)
class Square final : public Rectangle {
public:
    explicit Square(double s) : Rectangle(s, s) {}
    // draw() inherited from Rectangle - could override here
    // class SubSquare : public Square {}; ← compile error: final!
};

// ── How virtual dispatch works ────────────────────────────────
// Every object with virtual functions has a hidden 'vptr' field
// pointing to its class's vtable (array of function pointers).
//
// Shape*    → Shape's vtable:    [&Shape::area, &Shape::perimeter, ...]
// Circle*   → Circle's vtable:  [&Circle::area, &Circle::perimeter, ...]
// Rectangle*→ Rectangle's vtable:[&Rectangle::area, ...]
//
// shape_ptr->area()  →  shape_ptr->vptr[0]()   (runtime dispatch)
// Cost: one extra pointer dereference per virtual call

int main() {
    // Polymorphic container - shape type resolved at runtime
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(5.0));
    shapes.push_back(std::make_unique<Rectangle>(4.0, 3.0));
    shapes.push_back(std::make_unique<Square>(6.0));

    for (const auto& s : shapes) {
        s->draw();       // virtual dispatch - correct type called
        s->describe();   // non-virtual, but calls virtual area/perimeter
        std::cout << "
";
    }

    // sizeof: objects with virtuals have hidden vptr (usually 8 bytes)
    std::cout << "sizeof(Circle) = " << sizeof(Circle) << "
";
    // Typically: 8 (vptr) + 8 (radius) = 16 bytes

    return 0;
}

Common Mistakes

  • Not using `override` on derived virtual functions - `virtual void draw()` in derived with typo `void Draw()` compiles silently but doesn't override the base. With `override`: `void Draw() const override` gives a compile error 'does not override'. Always use `override`.
  • Calling virtual functions in constructors - during base construction, the derived class isn't yet set up. `virtual area()` called from `Shape::Shape()` calls `Shape::area()` (pure virtual → crash!), not `Circle::area()`. Never call virtual functions in constructors or destructors.
  • Performance myth about virtual calls - virtual dispatch adds ~1 nanosecond overhead per call (one extra pointer dereference). For millions of calls per second, consider devirtualisation. But for most application code, this cost is negligible and the design benefit far outweighs it.

Tip

Tip

Practice Virtual Functions vtable Mechanics in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Runtime Polymorphism: The hidden vptr pointer and Virtual Method Table resolution

Practice Task

Note

Practice Task - (1) Write a working example of Virtual Functions vtable Mechanics from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Virtual Functions vtable Mechanics is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • A **virtual function** enables **runtime polymorphism** - the correct function version is called based on the actual object type, not the pointer/reference type.
  • Not using `override` on derived virtual functions - `virtual void draw()` in derived with typo `void Draw()` compiles silently but doesn't override the base. With `override`: `void Draw() const override` gives a compile error 'does not override'. Always use `override`.
  • Calling virtual functions in constructors - during base construction, the derived class isn't yet set up. `virtual area()` called from `Shape::Shape()` calls `Shape::area()` (pure virtual → crash!), not `Circle::area()`. Never call virtual functions in constructors or destructors.
  • Performance myth about virtual calls - virtual dispatch adds ~1 nanosecond overhead per call (one extra pointer dereference). For millions of calls per second, consider devirtualisation. But for most application code, this cost is negligible and the design benefit far outweighs it.

Topics in This Module

0/6 done