Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating strings using "+" in c++ [duplicate]

I am a novice in C++ and i am referring Accelerated C++. While trying one of its exercise questions which says:

Are the following definitions valid? Why or why not?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;

When i tried & executed the program i am getting an error as:

invalid operands of types to binary operator +.

But the following code works perfectly fine:

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

I am not clear with its execution! why this concatenation in the first case not working?

Thanks!I am using DEV C++.

like image 876
poorvank Avatar asked Dec 05 '25 10:12

poorvank


1 Answers

In the first expression

"Hello" + ", world"

the compiler needs to find a suitable function such as operator+(const char *, const char *). No such function exists, so it cannot compile.

Conversely,

hello + ", world"

is looking for one matching operator+(const std::string&, const char*), and that overload does exist (it is provided by std::string).


Note that you even if you could write your own overload:

std::string operator+ (const char *left, const char *right)
{
    return std::string(left) + right;
}

(and you can't, as Praetorian points out) it wouldn't be a good idea.

Firstly, with primitive arguments, you'd lose ADL (ie, if the standard library put the operator in namespace std, it wouldn't normally be visible outside).

Secondly, if you have other libraries with their own string representations (eg. pre-STL stuff like RogueWave, or Qt, etc. etc.) they'd be equally justified in providing an overload for their string type, and the compiler would have no way to choose between them.

like image 116
Useless Avatar answered Dec 07 '25 01:12

Useless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!