[ACCEPTED]-A most vexing parse error: constructor with no arguments-standards

Accepted answer
Score: 62

Although MyClass myObj(); could be parsed as an object definition 7 with an empty initializer or a function 6 declaration the language standard specifies 5 that the ambiguity is always resolved in 4 favour of the function declaration. An empty 3 parentheses initializer is allowed in other 2 contexts e.g. in a new expression or constructing 1 a value-initialized temporary.

Score: 58

This is called the Most Vexing Parse issue. When the parser 3 sees

MyClass myObj();

It thinks you are declaring a function 2 called myObj that has no parameters and returns 1 a MyClass.

To get around it, use:

MyClass myObj;
Score: 20

I found this in the C++ standard (§8.5.8):

An 9 object whose initializer is an empty set 8 of parentheses, i.e., (), shall be value-initialized.

[Note: since 7 () is not permitted by the syntax for 6 initializer,

X a ();

is not the declaration of an 5 object of class X, but the declaration 4 of a function taking no argument and returning 3 an X. The form () is permitted in certain 2 other initialization contexts (5.3.4, 5.2.3, 12.6.2). —end 1 note ]

Score: 11

This is a fairly well known issue, and isn't 5 compiler dependent. Essentially, what you 4 were doing was declaring a function returning 3 type MyObj. Not surprisingly, you couldn't 2 call its constructor. See the C++ faq lite for a good 1 explanation

Score: 4
MyClass myObj();

That's parsed as a function declaration, the 5 function is called myObj, takes no arguments 4 and returns MyClass object. I've never seen 3 a compiler accepting that. On the other 2 hand MyClass* myPtr = new MyClass(); is acceptable, may be that got you 1 confused?

Score: 3

Your line makes the compiler think you are 3 declaring a function named myObj which takes 2 no arguments and returns a MyClass. This ambiguity 1 resolution is indeed annoying.

Score: 1

The standard does not require parentheses.

int* x = new int;

is 2 legal syntax.

In your case myclass myobj(); is a function 1 prototype. Whereas myclass myobj; is a variable.

More Related questions