0

I am very new to c++ programming. Been fiddling around with the string library and I came across something that stumped me.

FYI: This is an exercise from accelerated c++ for the strings chapter. I come from a java, javascript background and I don't see why the second statement does not compile, but the third does.

I am guessing it has to do something with strings working as const char[] arrays behind the scenes, but if somebody could explain why the second statement results in a compile time error and the third one compiles okay.

int main() {

    std::string exclam = "!";

    // Does not compile. Error: invalid operands of types 'const char [6]' and 'const char [8]' to binary 'operator+'
    std::string invalidMessage = "Hello" + ", world" + exclam; 

    // Works ... Why???
    std::string validMessage = exclam + "Hello" + ", World";        

    return 0;
}

If someone could explain to me what is happening here, would be very much appreciated. Thank you in advance!

J. Lee
  • 513
  • 4
  • 15
  • `decltype("Hello")` and `decltype("world")` will not give you `std::string`. They will give `const char[N]`, as compiler said. You can't concat them that way. Use `"Hello"s` to tell compiler to automatically convert it to string for concat – Incomputable Mar 17 '17 at 01:09
  • Thanks for the clarification. I ll do some more reading on this. Appreciate the help! – J. Lee Mar 17 '17 at 01:14

0 Answers0