Namara

Code daily. Without assist.

2026-08-20

dispatch.cpp

#include <iostream>

struct Base {
    virtual void greet(int n = 1) { std::cout << n; }
};

struct Derived : Base {
    void greet(int n = 2) override { std::cout << n; }
};

int main() {
    Base* b = new Derived();
    b->greet();
}

What does this print?

Answer

1. Virtual dispatch picks Derived::greet's body at runtime — that part is dynamic. But default argument values are bound statically, based on the declared type of the expression used to call, not the object's dynamic type. Since b is typed Base*, the default that gets used is Base's (n = 1), even though Derived::greet is what actually runs. Well-defined, and a very well-known trap.