Why does the compound assignment of a string and an int work, but the assignment of a string to a string + int doesn't in C++?

62 Views Asked by At

I'm learning C++ and I ran into an interesting predicament that I don't quite understand.

My goal is to concatenate a string with the char representation of an int value, say 'a'. My problem is that:

string a = "bo";
a = a + 97;

Doesn't work, yet

string a = "bo";
a += 97;

does.

I understand that one means add and the other means concatenate, but I've seen the example that states that

a += 1;

is the same as

a = a + 1;

Could someone please explain this?

1

There are 1 best solutions below

0
Sam Varshavchik On

I understand that one means add and the other means concatenate

Specifically, one is operator+ and the other is operator+=.

but I've seen the example that states that

a += 1;

is the same as

a = a + 1;

Could someone please explain this?

What's important to understand is that a particular class can implement its operator+ and operator+= overloads in whichever manner it feels like.

A given class can implement both overloads in a way that produces the same result, in this use case. But there is no explicit requirement in C++ to do so. There are certain generally accepted rules and idioms for operator overloading; however they are not mandates or dicta of some kind. As long as something is syntactically valid C++, anything goes.

A given class can implement its + overload to do one thing, and its += overload to do something else, in the manner that will not produce the same result, in this use case. Or, even, one may compile and the other one not compile, for some particular reason.

This is entirely up to the class.