Question

In C++, I'm trying to understand why you don't get an error when you construct a string like this:

const string hello = "Hello";
const string message = hello + ", world" + "!";

But you do get a compile time error with this:

const string exclam = "!";
const string msg =  "Hello" + ", world" + exclam

Compile time error is:

main.cpp:10:33: error: invalid operands of types ‘const char [6]’ and 
‘const char [8]’ to binary ‘operator+’

Why is the first run fine but the second produce a compile time Error?

Was it helpful?

Solution

It will make more sense if you write it out:

hello + ", world" + "!"; looks like this:

operator+(operator+(hello, ", world"), "!");

While

"Hello" + ", world" + exclam looks like this

operator+(operator+("Hello" , ", world"), exclam);

Since there is no operator+ that takes two const char arrays, the code fails.

However, there is no need for one, as you could concatenate them like the following (note I just removed the + sign):

const string msg =  "Hello" ", world" + exclam
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top