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,463
  • 1
  • 20
  • 29
Tyler
  • 389
  • 3
  • 8
  • 18

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
  • 135,913
  • 89
  • 401
  • 325
Jesse Good
  • 48,564
  • 14
  • 115
  • 165
  • 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