Possible Duplicate:
What are the basic rules and idioms for operator overloading?
Operator overloading : member function vs. non-member function?
After many years of apparently abusing this construct somebody pointed out to me that this is bad practice:
class SomeClass
{
...
bool operator<(const SomeClass& other) const;
};
whereas this is good practice:
class SomeClass
{
...
};
bool operator<(const SomeClass& a, const SomeClass& b);
But I can’t for the life of me figure out why and can’t find any docs on the difference. Can anyone point me in the right direction?
The first thing is that there is no advantage in implementing the operator as a member function, and there can be advantages in doing it as a free function. In particular, a member function is not symmetric with respect to the types of the two operands, the left-hand-side (lhs) must be of the exact type of the class on which it is being called, while the right-hand-side (rhs) can use implicit conversions. In the case of free function operators, the same conversions can be applied to lhs and rhs.
Note that the main difference here are the implicit conversions, and that makes a difference only if your type can be implicitly converted from other types. If there are no implicit conversions into your type, then this point would be moot, but considering that there is no disadvantage in using a free function and there are advantages in some cases, I would use free functions whenever possible.
I wrote some time ago about operator overloading here, you might find some suggestions there.