Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading