5

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?

  • the two operations are the same only if they are defined to be the same, which for strings they are not – Neil Butterworth Oct 19 '22 at 23:22
  • `std::operator+` and `std::operator+=` are different functions. Take a look at their signatures to see what's happening. *Upd*: Found a dupe that explains it. – Evg Oct 19 '22 at 23:23
  • Ain't operator overloading a gas? – user4581301 Oct 19 '22 at 23:23
  • *I've seen the example that states that (blah) is the same as (blah)* You've probably missed the context in which in the examle are the same, such as when `a` is a primitive type. User defined operators (including the standard C++ library ones) are not required to have that same parity behavior. – Eljay Oct 19 '22 at 23:45

1 Answers1

1

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148