Daily C++ Puzzle 2

A declaration disguised as a variable

A short C++ program with a bug: a declaration disguised as a variable. The answer, the observed output, the fix, and the lesson are on this page.

#include <iostream>

struct Widget {
    Widget() {}
    void greet() { std::cout << "hi\n"; }
};

int main() {
    Widget w();
    w.greet();
}

Widget w(); does not declare a variable — it declares a function named w returning Widget. So w.greet() fails. GCC says so directly, and even suggests the fix:

warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]
error: request for member 'greet' in 'w', which is of non-class type 'Widget()'

This program does not compile, so there is no runtime output to quote.

Fix: Widget w; or Widget w{};.

Lesson: when a declaration can be read as a function, the compiler reads it as a function.

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.