5

I have found something wierd which I don't understand.

std::string a();

When printed out it returns 1. I have no idea where it came from. I thought a() is a constructor without arguments, but it looks like it isn't.

Where can I find information about this? and what is this?

And when trying to do std::string b(a); compiler shouts:

error: no matching function for call to ‘std::basic_string<char>::basic_string(std::string (&)())’

Explanation would be appreciated.

jaor
  • 831
  • 7
  • 18
  • 3
    Google "c++ most vexing parse". – Jon May 28 '13 at 10:19
  • 6
    See: http://en.wikipedia.org/wiki/Most_vexing_parse – Paul R May 28 '13 at 10:19
  • 4
    People, what are all the downvotes for? Is the answer so obvious that all of you immediately knew what the problem was when it bit you? Voting to close the question as a dupe is great, but let's not slap people around for not knowing. – Jon May 28 '13 at 10:21
  • 1
    @Jon: Maybe for some (including me, since I had a similar error message which revealed that it is a function(pointer) just like in the error in the post. Sometimes reading the error is useful), but I personally would say that it mostly does not show any research effort. – PlasmaHH May 28 '13 at 10:24
  • @PlasmaHH: IMHO that error message is useless if you are not reasonably experienced, most newbies that get this would have no fighting chance. That said, I respect your opinion (especially since you took the time to explain it!) and would not have commented if I had discovered that jaor has a habit of not researching. As it is, I think there is a case for giving them the benefit of the doubt. – Jon May 28 '13 at 10:32
  • @Jon: While recognizing that `std::string (&)()` is a reference to a function is indeed not easy, I would expect people to at least /try/ to understand it; if that was the case, the question should then probably be something like "I have no idea what this `std::string (&)()` thing, anyone can tell me?". Even a "I don't understand this error at all and no idea on where to start with it" would show effort, but as it is currently it reads more like (exaggerated) "here is an error, don't want to read it, explain it to me". Good thing here is that SO has a vote system so it captures many opinions. – PlasmaHH May 28 '13 at 10:45

2 Answers2

5

This is a function declaration, not a string instantiation:

std::string a();

It declares a function called a, with no parameters, and returning an std:string. These are instantiations:

std::string a;   // C++03 and C++11
std::string b{}; // C++11 syntax
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3
std::string a();

Declares a function with no arguments and std::string as return type. When you trying to print it, you print address, which is evaluating to true.

warning: the address of ‘std::string a()’ will always evaluate as ‘true’ [-Waddress]

awesoon
  • 32,469
  • 11
  • 74
  • 99