5

The following code will compile and is deterministic according to cppquiz.org (Question #30)

#include <iostream>
struct X {
  X() { std::cout << "X"; }
};

int main() { X x(); }

The output of the program is nothing, as

X x();

is a function declaration.

But still I wonder why this compiles though this declaration is never defined anywhere?

2
  • 4
    It would compile even if you did call x. It wouldn't link, though. Commented Jun 25, 2014 at 17:39
  • 1
    ... because it is not used anywhere either Commented Jun 25, 2014 at 20:00

2 Answers 2

6

Since x() is never called, there's nothing to link so no error from linker that it's not defined. It's only declared as a function taking no arguments and returning an X: X x();.

Sign up to request clarification or add additional context in comments.

Comments

3

X x(); itself a declaration (prototype), not a function call. If a function call is made prior to seeing its declaration then it would not compile.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.