Search code examples
c++constructortemporary-objects

Pass temporary object with standard constructor


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?


Solution

  • This is an instance of what has been dubbed C++'s most vexing parse. The compiler interprets

    MyClass a(string());
    

    as the prototype of a function named a returning a MyClass and taking an unnamed string as a parameter.

    You can disambiguate it by putting parenthesis around the call to strings constructor:

    MyClass a((string()));
    

    Or, as long as MyClass has an accessible copy constructor:

    MyClass a = string();
    

    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:

    MyClass a { string() };