I do not understand why this compiles

C++SyntaxDeclarationMost Vexing-Parse

C++ Problem Overview


I'm certainly missing something, but I do not understand why this compiles (with both g++ & clang++):

struct A
{
};
struct B
{
};

int main()
{
  A a(B);
}

First of all, B is a type... not a value. How should I interpret this code?

C++ Solutions


Solution 1 - C++

It's interpreted as the declaration of a function named a, which takes one argument of type B and returns A.

Solution 2 - C++

It's simply a function declaration declaring a to be a function returning A and taking one unnamed parameter of type B.

It is valid because function declarations as opposed to function definitions are allowed within function definitions.

Solution 3 - C++

This issue is known as the most vexing parse. The line A a(B); can be interpreted as the declaration of a function named a returning an object of type A and taking an unnamed parameter of type B.

One way to avoid this issue is to use the uniform initialization syntax which was introduced in C++11, which consists in using braces instead of parenthesis: A a{B}; returns an error. The line is now interpreted as a variable declaration initialized with B, which is a type instead of a value.

Here's more information:

The Most Vexing Parse: How to Spot It and Fix It Quickly

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
QuestionPicaud VincentView Question on Stackoverflow
Solution 1 - C++Brian BiView Answer on Stackoverflow
Solution 2 - C++machine_1View Answer on Stackoverflow
Solution 3 - C++GuilmoView Answer on Stackoverflow