Search code examples
c++stringoperator-overloadinguser-defined-types

Adding strings and literals (C++)


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;
}
  • Question 1: Why does example 1 generate an error, since both operands are string literals?
  • Question 2: Why is it that at least one of the operands must be a string?
  • Question 3: Why does example 2 also generate an error?

I just want to understand what's going on behind the scenes.


Solution

  • 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';