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?
Join Stack Overflow to learn, share knowledge, and build your career.
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?
It's interpreted as the declaration of a function named a
, which takes one argument of type B
and returns A
.
A a{B};
– user4581301
Dec 3 '19 at 17:46
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.
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:
struct A { };
are not valid in standard C, even if some compilers allow them. Drop the braces and there wouldn't be a problem there. Also, in C, declaring or defining struct A
does not create a type name A
(you must prefix it with struct
, or add typedef struct A A;
somewhere before A
is used without the struct
prefix). Also in C, there is no alternative parse to the function declaration — using type name(...);
simply cannot ever be a variable definition; it is always a function declaration (or invalid). The code in the question is not valid in C.
– Jonathan Leffler
Dec 10 '19 at 22:25
A a(B());
which could be a variable definition or function declaration. – walnut Dec 3 '19 at 17:51struct A{}; int main() { A(foo); }
compiles as is, even iffoo
doesn't name anything. – Ayxan Haqverdili Dec 3 '19 at 17:56