I have this code:
#include <iostream>
using namespace std;
int main()
{
string name = "John ";
int age = 32;
name += age;
cout << name << endl;
return 0;
}
The code compiles successfully but betrays at run time as it silently ignores the concatenation part and prints:
John
I know that we need to use stringstream for the task. But why does the above code compile? Because the following code:
#include <iostream>
using namespace std;
int main()
{
string name = "John ";
int age = 55;
name = name + age;
cout << name << endl;
return 0;
}
duly throws and error:
error: no match for ‘operator+’ in ‘name + age’
I know from Java that a += b
is different from a = a + b
as the former construct typecasts the result to the type of a. Reference. But I don't think this would matter in C++ as we can always do:
int a = 1;
float f = 3.33;
a = a + f;
without worrying about a possible loss of precision warning unlike Java. Need citation for this in C++.
So now if we assume that name += age;
expands to name = string (name + age);
then also the code should not have compiled simply because name + age is not legal.