2

I was going through the documentation for STL strings at - http://www.cplusplus.com/reference/string/string/.

In it, I found that the relational operators are overloaded as non-member functions. Is there any reason why they are overloaded as non-member functions as opposed to member functions?

2
  • Just to mention that cplusplus.com is very old (it targets C++11). en.cppreference.com is more up to date. Commented Sep 21, 2019 at 1:24
  • Note that you should not rely on the relational operators being member functions or non-member functions. All that you should rely on is that the expression a < b (and related ones) is valid and does what we expect. Commented Sep 21, 2019 at 1:25

1 Answer 1

3

Overloading them as non-member functions allows the LHS of the operator to be converted to type std::string. For example, the following does not work should operator== be a member:

std::string name = "foo"; if ("foo" == name) // ... 

That's because "foo".operator==(name) is not a valid expression.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.