Geobor
Geobor

Reputation: 33

Which overload does an operator use in C++?

Everybody knows that you can't concatenate 2 string literals using the + operator.

#include <iostream>

int main() {
  std::cout << "hello " + "world";
}
// Error

What's happening here is that you are trying to add 2 char* which is an error. You can however add a string literal to a std::string.

#include <iostream>

int main() {
  std::string s = "hello ";
  std::cout << s + "world";
}
// Fine, prints hello world

But what I found is that the below code is also valid.

#include <iostream>

int main() {
  std::string s = "world";
  std::cout << "hello " + s;
}
// Fine, prints hello world

I would imagine in the above example that you are trying to add a std::string to a char* but it works fine. I think it may just be using the std::string overload of the + operator. My question is what exactly is happening here and how does the operator decide which overload to use in a situation such as with 2 different classes with perfectly valid overloads being added together.

Upvotes: 3

Views: 132

Answers (2)

eerorika
eerorika

Reputation: 238461

What's happening here is that you are trying to add 2 char* which is an error.

To be a bit more correct, you're trying to add two arrays, each of which decay to const char*.


My question is what exactly is happening here

You're using these overloads:

std::string
operator+(const std::string& lhs, const char* rhs);

std::string
operator+(const char* lhs, const std::string& rhs);

how does the operator decide which overload to use

It uses the same overload resolution as normal functions do. The complete and precise description won't fit within this answer since overload resolution is quite complex.

In short: There is a list of all functions by the same name. This is the overload set. If all arguments (operands in case of operator overload) can be converted to the formal parameters of the function, then that function is a viable candidate for the overload resolution. The candidates are ranked by a set of rules. Candidate requiring "less" conversion is ranked higher. If one candidate is unambiguously the most highly ranked candidate, then that overload will be called; otherwise there is an error.

Upvotes: 7

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123431

Operator precedence : + has higher rank than <<, hence the line is parsed as:

(std::cout <<  ("hello " + s) );

And operator+(const char*,const std::string&) is the one on place 4 here: https://en.cppreference.com/w/cpp/string/basic_string/operator%2B.

Maybe you are a little surprised, because often operators are member functions and that implies that the left operand would need to be the std::string. However, thats not always the case. Operators can be free functions.

Upvotes: 3

Related Questions