Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A most vexing parse error: constructor with no arguments

I was compiling a C++ program in Cygwin using g++ and I had a class whose constructor had no arguments. I had the lines:

MyClass myObj(); myObj.function1(); 

And when trying to compile it, I got the message:

error: request for member 'function1' in 'myObj', which is of non-class type 'MyClass ()()'

After a little research, I found that the fix was to change that first line to

MyClass myObj; 

I could swear I've done empty constructor declarations with parentheses in C++ before. Is this probably a limitation of the compiler I'm using or does the language standard really say don't use parentheses for a constructor without arguments?

like image 621
mring Avatar asked Feb 23 '10 14:02

mring


People also ask

What is vexing parse?

Noun. most vexing parse. (programming) A specific form of syntactic ambiguity resolution in the C++ programming language, whereby attempts to declare a variable may be undesirably interpreted as attempts to declare a function.

How do you write a parameterized constructor in C++?

To create a parameterized constructor, it is needed to just add parameters as a value to the object as the way we pass a value to a function. Somewhat similar scenario we do by passing the parametrized values to the object created with the class.


2 Answers

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

like image 143
CB Bailey Avatar answered Oct 16 '22 04:10

CB Bailey


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

MyClass myObj(); 

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

To get around it, use:

MyClass myObj; 
like image 31
Peter Alexander Avatar answered Oct 16 '22 05:10

Peter Alexander