Why does this call the default constructor?

C++SyntaxMost Vexing-Parse

C++ Problem Overview


struct X
{
    X()    { std::cout << "X()\n";    }
    X(int) { std::cout << "X(int)\n"; }
};

const int answer = 42;

int main()
{
    X(answer);
}

I would have expected this to print either

  • X(int), because X(answer); could be interpreted as a cast from int to X, or
  • nothing at all, because X(answer); could be interpreted as the declaration of a variable.

However, it prints X(), and I have no idea why X(answer); would call the default constructor.

BONUS POINTS: What would I have to change to get a temporary instead of a variable declaration?

C++ Solutions


Solution 1 - C++

> nothing at all, because X(answer); could be interpreted as the declaration of a variable.

Your answer is hidden in here. If you declare a variable, you invoke its default ctor (if non-POD and all that stuff).

On your edit: To get a temporary, you have a few options:

Solution 2 - C++

The parentheses are optional. What you said is identical to X answer;, and it's a declaration statement.

Solution 3 - C++

If you want to declare a variable of the type X, you should do it this way:

X y(answer);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfredoverflowView Question on Stackoverflow
Solution 1 - C++XeoView Answer on Stackoverflow
Solution 2 - C++Kerrek SBView Answer on Stackoverflow
Solution 3 - C++huysentruitwView Answer on Stackoverflow