2

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.

1
  • @vlad OK, i understand. removed discussion Commented Nov 18, 2019 at 12:35

3 Answers 3

3

In the first case, "hello" and "world" are not std::strings! The way you write them, they are char-arrays.

A way to overcome this is by explicitly defining them as string literals:

string welcome = "hello "s + "world"s;    //example 1

This is part of std::string, defined as operator"". But you need to add using namespace std::string_literals; to be able to use it.

The rest is explained in other answers.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Or auto welcome = "hello "s + "world"; (after using namespace std::string_literals;)
1

Literals strings are really arrays of constant characters. As such they decay to pointers to their first elements. Adding two string literals is adding those pointers. The result is a pointer to some totally unrelated location.

For characters, they first get promoted to int then they are added as integers and the result is an int.


For the first example, when you do "hello " + "world" that's actually equivalent to &(("hello ")["world"]). This doesn't make any sense, and neither does adding the literal strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.