I’d like to pass a temporary object(std::string for example) to the constructor of my object:
class MyClass{
public:
MyClass(string a):
a(a)
{
}
string a;
};
int main(int argc, char *argv[]){
MyClass a(string());
cout<<a.a<<endl;
return 0;
}
But I receive this error:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:28:11: error: request for member ‘a’ in ‘a’, which is of non-class type ‘MyClass(std::string (*)()) {aka MyClass(std::basic_string<char> (*)())}’
Everything works ok if I pass anything to the constructor of temporary object(for example string(“”)). Why?
This is an instance of what has been dubbed C++’s most vexing parse. The compiler interprets
as the prototype of a function named
areturning aMyClassand taking an unnamedstringas a parameter.You can disambiguate it by putting parenthesis around the call to
strings constructor:Or, as long as
MyClasshas an accessible copy constructor:Update for C++11
You can also disambiguate with the universal initialisation syntax, as long as your class doesn’t have a constructor that takes an
initializer_list: