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?

pranav
  • 163
  • 1
  • 3
  • 12
  • Just to mention that cplusplus.com is very old (it targets C++11). https://en.cppreference.com is more up to date. – L. F. Sep 21 '19 at 01: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. – Justin Sep 21 '19 at 01:25

1 Answers1

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.

L. F.
  • 19,445
  • 8
  • 48
  • 82