Aswin
Aswin

Reputation: 147

Operator Overloading of + in C++

I was recently playing with strings, and I have come across a strange issue. During Operator overloading with + for String concatenation. I have tried to overload with two chars to a string. It returns me a peculiar behaviour.

string a = 'den';
a+='e'+'r';

I expect the result to be dener. But,it returns den╫. I like to know, what went wrong my approach. It works when, I tried it separate line, like below.

string a = 'den';
a+='e';
a+='r';

I got answer from a different question. But, I am repeating here, for anywork around to solve my problem.

Upvotes: 0

Views: 112

Answers (2)

Alexandru Ica
Alexandru Ica

Reputation: 139

You are adding two characters which are numbers. 'e' + 'r' is computed first and since 'e' is 101 in ASCII and 'r' is 114 you are concatenating the character with the code 215. To concatenate "er":

string a = "den";
a += 'e';
a += 'r';

Upvotes: -1

YSC
YSC

Reputation: 40060

a+='e'+'r';

There are two operators involved. By their association rules, they work in the following order:

  1. 'e'+'r' is computed
  2. a += result#1 is computed.

About 1.: this is the sum of two objects of type char, and it happends that their sum on your system is 1.

Finally, std::string::operator+= is invoked and is appended to your string.

What you really want is one of the following:

a += "er";
// or
a += 'e';
a += 'r';
// or
for (char c : your_char_array) {
    a += c;
}
// or
a += your_char_array;

1) If you were on an ASCII OS, as 'e' is 101 (decimal) and 'r' is 114 (decimal), their sum is 215 (decimal) which stands for 'Î' in extended ASCII.

Upvotes: 2

Related Questions