String concatenation

Viewed 4613

Why it is possible to do

const string exclam = "!";
const string str = exclam + "Hello" + " world";

And not possible to do this:

const string exclam = "!";
const string str = "Hello" + " world" + exclam;

I know (although can't understand why) that it is not allowed to do:

const string str = "Hello" + " world" + "!";

as it will be interpreted like const char[6] + const char[6] + const char[1], so from other side, why this is not allowed also, or why it uses char[] and not string.

5 Answers

In addition to the answers that explain the reason for your observations, I post here how to get rid of the problem (you might have figured this out already).

Replace

const string str = "Hello" + " world" + exclam;

with

const string str = string("Hello") + " world" + exclam;

so you make sure the first operand is a string and not a const char[].

Related