I do not understand why this compiles
Solution 1:
It's interpreted as the declaration of a function named a
, which takes one argument of type B
and returns A
.
Solution 2:
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:
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