Based on my reading, the following code:
string aggregate = "give" + 'n';
Should produce a resulting string with the value:
“given”.
It instead produces garbage. Why doesn’t the following happen?
-
“give” is converted to a std::string via the constructor that takes a pointer to a character array.
-
The ‘+’ overload that takes a std::string and a character is called, returning a new string.
I am basing my theory on this man page.
Now, I have heard that the first argument to an overloaded operator isn’t a candidate for constructor conversion if the operator is a member of a class. I believe I read that in Koenig and Moo. But, in this case I understand the ‘+’ operator to be a non-member overload.
I realize this seems like a ridiculous over-complication, but I like to know FOR SURE what is happening when I write code.
The expression
"give" + 'n'is evaluated first, adding(int)'n'to the address of the string constant"give". The result of this pointer arithmatic is assigned to the string object. No error is raised because the result is of typeconst char*.You should get used to thinking of everything on the right of the
=as happening before the actual assignment (or initialization in this case).You want the following:
or, explicitly build the a string object first: