Pure luck.
When you use your character array this context
string str1 = charArray + string("string")
the array is interpreted as a C-style string.
C-style strings are terminated by zero character value. In your case the first uninitialized array element (i.e. charArray[4]
in the first experiment) just happened to be zero by pure luck (assuming this is a local array). That accidental zero in charArray[4]
worked as zero-terminator for the string, so your charArray
happened to stand for a valid C-string "abcd"
. That's exactly what you see.
The same thing happens in the second experiment.