Why is this an issue?
Member functions can only be used with an instance of a class. But friend
functions can be used with an implicitly converted type. So
loosening access privileges to friend
on overloaded binary operators makes them more flexible. Specifically, with a friend
function, the class instance can be on either the right or the left of the operator, but with a member function, it can only be on the left.
This rule raises an issue for all non-friend
overloaded binary operators except:
- "
=
", "[ ]
", and "->
", which cannot be overloaded as friend
functions.
- "
+=
", "-=
", "*=
", "/=
", "%=
", "^=
", "&=
",
"|=
", "<<=
", and ">>=
", which are not symmetric operators.
Noncompliant code example
bool operator==(const MyClass &RHS); // Noncompliant
Compliant solution
friend bool operator==(const MyClass &LHS, const MyClass &RHS);
Resources