0

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?

neatnick
  • 1,489
  • 1
  • 18
  • 29
Tyler
  • 509
  • 4
  • 11
  • 23

1 Answers1

7

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
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • Thank you, so it is kind of an order of operations thing. I kept finding that you can't do it, but not precisely why you can't. – Tyler Sep 14 '13 at 04:12