Daily C++ Puzzle 3

The derived object that arrived as a base

A short C++ program with a bug: the derived object that arrived as a base. The answer, the observed output, the fix, and the lesson are on this page.

#include <iostream>

struct Base {
    virtual void who() { std::cout << "base\n"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    void who() override { std::cout << "derived\n"; }
};

void show(Base b) { b.who(); }

int main() {
    Derived d;
    show(d);
}

show takes Base by value, so the Derived is copied into a Base — sliced. The derived part is gone before who() runs, and virtual dispatch on the sliced copy calls the base version.

Observed output: base.

Fix: take const Base&.

Lesson: pass polymorphic objects by reference, never by value.

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.