In the book C++ Primer I came across the statement: "When we mix strings and string or character literals, at least one operand to each + operator must be a string type"
I noticed the following were not valid:
#include<string>
int main()
{
using std::string;
string welcome = "hello " + "world"; //example 1
string short_welcome = 'h' + 'w'; //example 2
return 0;
}
I just want to understand what's going on behind the scenes.
You may overload operators only for user-defined types as for example the class std::string
.
So these operators for fundamental types
"hello " + "world"
'h' + 'w'
can not be overloaded.
In the first expression the string literals are converted to pointers to their first elements. However the binary operator + is not defined for pointers.
In the second expression the character literals are converted to integers and the result is an integer. However the class std::string has no implicit constructor that accepts an integer.
You could write for example
string welcome = std::string( "hello " ) + "world";
or
string welcome = "hello " + std::string( "world" );
or
string short_welcome( 1, 'h' );
short_welcome += 'w';