Search code examples
c++stdstring

how adding string and numbers in cpp works using + operator?


I've used cpp for quite a while, I was known that we cannot add string and numbers(as + operator is not overloaded for that). But , I saw a code like this.

#include <iostream>
using namespace std;
int main() {
    string a = "";
    a += 97;
    cout << a;
}

this outputs 'a' and I also tried this.

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

The second code gives a compilation error(as invalid args to + operator, std::string and int). I don't want to concatenate the string and number. What is the difference? Why does one work but not the other?

I was expecting that a+=97 is the same as a=a+97 but it appears to be different.


Solution

  • The first snippet works because std::string overrides operator+= to append a character to a string. 97 is the ASCII code for 'a', so the result is "a".

    The second snippet does not work because there is no + operator defined that accepts a std::string and an int, and no conversion constructor to make a std::string out of an int or char. There two overloads of the + operator that take a char, but the compiler cannot tell which one to use. The match is ambiguous, so an error is reported.