Vicente Bermúdez
Vicente Bermúdez

Reputation: 344

'+' cannot add two pointers error

I can do what the following code shows:

std::string a = "chicken ";
std::string b = "nuggets";
std::string c = a + b;

However, this fails:

std::string c = "chicken " + "nuggets";

It gives me an error saying " '+' cannot add two pointers". Why is that so? Is there an alternative way to do this without getting an error?

Upvotes: 4

Views: 2722

Answers (3)

Jarod42
Jarod42

Reputation: 218323

"chicken " and "nuggets" are literal C-string and not std::string.

You may concatenate directly with:

std::string c = "chicken " "nuggets";

Since C++14, you may add suffix s to have string

using namespace std::string_literals;
std::string c = "chicken "s + "nuggets"s;

Upvotes: 14

Hcorg
Hcorg

Reputation: 12178

Both "chicken" and "nuggets" has type const char* (as literals in code). So you are trying to add to pointers.

Try std::string c = std::string("chicken") + "nuggets";

std::string is not part of language itself, it's a part of standard library. C++ aims to have as few language features as possible. So built-in type for strings is not present in parser etc. That's why string literals will be treaded as pointers.

EDIT

To be completely correct: type of literals is really const char[N] (where N is character count in literal +1 for \0. But in C++ arrays ([]) can be treated as pointers, and that is what compiler tries to do (as it cannot add arrays)

Upvotes: 4

NathanOliver
NathanOliver

Reputation: 181068

"chicken " and "nuggets" are not of type std::string but are const char[]. As such even though you want to assign the concatenation to a string they types don't have an operator +. You could solve this using:

std::string c = std::string("chicken ") + "nuggets";

Upvotes: 6

Related Questions