2

Possible Duplicate:
Is no parentheses on a constructor with no arguments a language standard?

Can anyone explain why these line don't give me an error:

string params;
params+="d";

but these lines:

string params();
params+="d";

give me this error: error C2659: '+=' : function as left operand

Community
  • 1
  • 1
kakush
  • 3,334
  • 14
  • 47
  • 68

2 Answers2

7

This is not object:

 string params();

This is function returning string:

 string params();

Like this:

 string params(void);

So the error now is obvious: function as left operand

This problem has own name: http://en.wikipedia.org/wiki/Most_vexing_parse

PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
  • so string params() is not an object but string params("word") is an object? – kakush Oct 16 '12 at 09:07
  • @kakush Yes - "word" is not type - it is value - so it is object. When compiler is in doubt if the expression is function declaration or object - it always select function declaration. In your example with "word" - there is no doubt. – PiotrNycz Oct 16 '12 at 09:09
  • thanks @PiotrNycz . so if I want to use string's empty const' how do i do that? – kakush Oct 16 '12 at 09:12
  • 1
    @kakush: you write `string params;`, which calls the class's default constructor if it has one declared (`string` does). If you want some type `T` that might not have a constructor at all (for instance built-in types), you can write `T t = T();` provided that it's copyable (or movable in C++11). If you have a type that *either* has a declared default constructor *or* is copyable, but you don't know which, then in C++03 you have a problem. In C++11 you can write `T t{};` to value-initialize anything. – Steve Jessop Oct 16 '12 at 09:15
1

In the first case with the

string params;

creates a string instance using a default constructor.

In the second case the

string params();

creates a pointer to a function returning string. On that type the operator+=(const string&) is apparently not defined.

Yes, it is a bit confusing feature of the language because when you use not default constructor, you could really write e.g.

string params("d");
David L.
  • 3,149
  • 2
  • 26
  • 28