Virtual Functions in C++: Runtime Polymorphism with Worked Traces

Follow one C++ program from a base pointer to three runtime-selected results. Then test the same rules against pure virtual functions, default arguments, slicing, construction, and destruction.

KnowledgeGate Team

Exam prep & CS education

Updated 15 Nov 20266 min read
Virtual Functions in C++: Runtime Polymorphism with Worked Traces

Base *p = &derived often causes confusion: the pointer has a base type, yet p->f() can execute the derived implementation. The answer depends on the pointer's static type, the object's dynamic type, and virtual. For input 4, the calls produce 5, 8, and 16, for a total of 29. Pure contracts, default arguments, slicing, construction and destruction can change the selected function or make an operation invalid.

Virtual functions connect a base interface to runtime behaviour

A virtual function is a non-static member declared virtual in a base class. When called through a suitable pointer or reference, the dynamic type determines which final overrider runs. One base interface can therefore produce different behaviour for different derived objects.

In Operation *p = &twice, p has static type Operation*, while *p has dynamic type DoubleOp. The compiler validates Operation::apply(int) const; runtime selects DoubleOp::apply(int) const.

Overriding replaces a base virtual implementation, while overloading chooses among parameter lists at compile time. Coding & Skill Development Courses places C++ in a broader programming route. For a compact first-principles dispatch and VTable model, use Virtual Functions and VTable in C++: Runtime Dispatch with Runnable Examples. C++ Virtual Functions and Polymorphism: Trace Dynamic Dispatch Step by Step owns the Shape hierarchy, override/final rules, and the basic slicing trace. Operation and Fare traces isolate different boundaries: pure contracts, statically bound defaults, constructor-state dispatch, and by-value slicing.

Worked C++ example: one interface, three exact results

Three different objects sit behind pointers of the same base type:

cpp
#include <iostream>

class Operation {
public:
    virtual int apply(int x) const { return x + 1; }
    virtual ~Operation() = default;
};

class DoubleOp : public Operation {
public:
    int apply(int x) const override { return 2 * x; }
};

class SquareOp : public Operation {
public:
    int apply(int x) const override { return x * x; }
};

int main() {
    Operation base;
    DoubleOp twice;
    SquareOp square;
    Operation *ops[] = {&base, &twice, &square};

    int total = 0;
    for (Operation *p : ops) {
        int value = p->apply(4);
        std::cout << value << ' ';
        total += value;
    }
    std::cout << "\ntotal = " << total << '\n';
}

Trace the loop one pointer at a time:

  1. p = &base selects Operation::apply(4), so 4 + 1 = 5.

  2. p = &twice selects DoubleOp::apply(4), so 2 x 4 = 8.

  3. p = &square selects SquareOp::apply(4), so 4 x 4 = 16.

The sum is 5 + 8 + 16 = 29. The exact output is:

Code
5 8 16
total = 29

The override specifier does not make the base function virtual; it makes the compiler reject a derived signature that does not override. Matching derived overrides remain virtual without the word, but keeping override is safer.

How virtual dispatch chooses the final overrider

The call has two stages. At compile time, static type Operation* finds and type-checks apply(int) const. At runtime, the dynamic object selects Operation::apply, DoubleOp::apply, or SquareOp::apply. This is dynamic dispatch, or late binding.

Remove virtual and both override specifiers, and every call through Operation* uses Operation::apply(4): output 5 5 5, total 15. Keep override after removing base virtual, and compilation fails as intended.

Three-lane dispatch trace of the ops array: the base object gives 4 + 1 = 5, DoubleOp gives 2 x 4 = 8, SquareOp gives 4 x 4 = 16, total 29.

Pure virtual functions turn the base into an interface

An abstract base can state the contract without providing a usable object:

cpp
class Fare {
public:
    virtual int cost(int km) const = 0;
    virtual ~Fare() = default;
};

The = 0 makes cost pure virtual and Fare abstract. Thus Fare f; is ill-formed, but Fare pointers and references remain useful. Suppose Bus::cost(int km) const override returns 5 * km, while Metro::cost(int km) const override returns 8 * km + 10.

With Bus bus; Metro metro; Fare *routes[] = {&bus, &metro}; and km = 8, the bus result is 5 x 8 = 40. The metro result is 8 x 8 + 10 = 64 + 10 = 74. Together they produce 40 + 74 = 114.

The pure virtual base supplies a stable contract; each concrete class implements it. A virtual function need not be pure for runtime dispatch, and an abstract class need not be a zero-data interface. Abstract Classes in C++: Pure Virtual Functions, Examples and Errors owns the fuller treatment of base-owned state, composition, and implementation errors; the Fare calculation isolates selection through a pure contract.

Override signatures and default arguments create exam traps

Signatures must match. If a base declares virtual int score() const { return 10; } but the derived class writes int score() { return 30; }, missing const makes it different. With override, the compiler rejects it. Without override, a base pointer calls the base const function and returns 10. Repair it with int score() const override { return 30; }.

Default arguments follow a different rule:

cpp
struct Base {
    virtual int fee(int x = 10) const { return x + 1; }
};
struct Derived : Base {
    int fee(int x = 20) const override { return 2 * x; }
};
Derived d;
Base *p = &d;

For p->fee(), static type Base* supplies default 10; runtime selects Derived::fee, producing 2 x 10 = 20. For d.fee(), static type Derived supplies 20, producing 2 x 20 = 40. Default arguments bind statically; virtual function bodies are selected dynamically.

Pointers and references preserve polymorphism; copying can slice it

Reuse DoubleOp twice. Operation &byRef = twice; byRef.apply(4) returns 8; Operation *byPtr = &twice; byPtr->apply(4) also returns 8. Both designate the existing DoubleOp object.

Copy it with Operation byValue = twice;. The new object contains only the Operation base subobject, so its dynamic type is Operation and its call returns 4 + 1 = 5. Losing the derived part is object slicing.

Parameter passing shows the same contrast. int run(Operation op) { return op.apply(4); } returns 5 for twice because the parameter is sliced. int runRef(const Operation &op) { return op.apply(4); } returns 8 because the reference preserves the dynamic object. For polymorphic APIs, prefer references for observation or smart pointers for shared ownership.

Two panels: a reference and a pointer to DoubleOp both dispatch to 2 x 4 = 8, while a sliced by-value copy dispatches to 4 + 1 = 5.

Construction, destruction, and representative exam traces

A base intended for polymorphic deletion needs a virtual destructor. For struct Base { virtual ~Base() { std::cout << "~Base\n"; } }; struct Derived : Base { ~Derived() override { std::cout << "~Derived\n"; } }; Base *p = new Derived; delete p;, deletion prints ~Derived, then ~Base. Without the virtual base destructor, deleting through Base* has undefined behaviour; do not assume only ~Base prints.

Construction also changes dispatch. If a Base constructor prints virtual f() returning 1, then the Derived constructor prints f() returning 2, constructing a Derived prints 1 2. The base constructor cannot dispatch into the unconstructed derived part; the derived constructor body can select its override.

Exam traces ask for output through a base pointer, a missing virtual, an overload-versus-override distinction, a sliced value, or deletion through a base pointer. Constructor calls stay within the class currently under construction, while defined polymorphic deletion runs from derived to base.

Virtual functions in C++: the short trace and next step

Before tracing a call, ask five questions:

  1. Is the base member virtual?

  2. Is the call through pointer or reference?

  3. Which signature and default does the static type select?

  4. Which dynamic type supplies the final overrider?

  5. Did slicing, construction, or destruction change the context?

Name the binding rule before computing each look-alike case:

Context

Binding rule

Exact result

Operation *p = &twice; p->apply(4)

Dynamic final overrider

DoubleOp::apply(4) = 8

Base *p = &d; p->fee()

Base default, derived body

2 x 10 = 20

Operation byValue = twice; byValue.apply(4)

Sliced dynamic type

Operation::apply(4) = 5

Base constructor calls f()

Current construction stage

Base::f() = 1

delete p for virtual Base::~Base()

Dynamic destruction, then bases

~Derived, then ~Base

One self-test uses input 6: Operation *p = &square; p->apply(6) is 36; Operation &r = twice; r.apply(6) is 12; Operation sliced = twice; sliced.apply(6) is 7. Their total is 36 + 12 + 7 = 55.

Reproduce 5 8 16 and total 29, then change only the dynamic objects. Continue with the C++ Programming Course: Concepts, MCQs & Coding for structured study.