Autechre
Autechre

Reputation: 604

How the C++ most vexing parse is possible in this example?

I read that this code A a( A() ); was interpreted by the compiler as a function declaration while here I clearly see that A() is a function that returns an object. How can it be something else that the construction of a A object ?

I've just read entirely the Function declaration page of cppreference : https://en.cppreference.com/w/cpp/language/function and I don't see anywhere that the parameters list can look like that A().

I don't understand how The most vexing parse can be valid C++.

Upvotes: 3

Views: 165

Answers (1)

Nathan Pierson
Nathan Pierson

Reputation: 5565

A() isn't a function declaration by itself, but it can be the type of a function.

For instance, suppose I declare the following function: A makeAnA();. The type of makeAnA is A(): A function that takes no arguments and returns an A.

Quoting cppreference on functions:

Each function has a type, which consists of the function's return type, the types of all parameters (after array-to-pointer and function-to-pointer transformations, see parameter list) , whether the function is noexcept or not (since C++17), and, for non-static member functions, cv-qualification and ref-qualification (since C++11). Function types also have language linkage.

So a function that has zero parameters, returns an A, and isn't noexcept has the type A().

Therefore, it's possible to interpret A a( A() ); as a function declaration. It declares that a accepts a single, unnamed argument of type A(), and returns an A as its result. Because it's possible to interpret this as a function declaration, it is required by the standard that it is so interpreted.

Upvotes: 6

Related Questions