views:

106

answers:

3

Why is that sometimes an operator override is defined as a method in the class, like

MyClass& MyClass::operatorFoo(MyClass& other) { .... return this; };

and sometimes it's a separate function, like

MyClass& operatorFoo(MyClass& first, MyClass& bar)

Are they equivalent? What rules govern when you do it one way and when you do it the other?

+1  A: 

If the operator is defined outside of a class it's considered global, and allows you to have other types appear on the left hand side of the operator.

For example, given a class Foo, with a global operator + you could do:

Foo f;
Foo f2 = 55 + f;
Charles Salvia
+10  A: 

If you want to be able to do something like 3 + obj you have to define a free (non-member) operator.

If you want to make your operators protected or private, you have to make them methods.

Some operators cannot be free functions, e.g., operator->.

This is already answered here:

http://stackoverflow.com/questions/1145022

Tim Sylvester
+5  A: 

If you have a binary operator like +, you normally want type conversions to be performed on both operands. For example, a string concatenation operator needs to be able to convert either or both of its operands from a char * to a string. If that is the case, then it cannot be a member function, as the left hand operand would be *this, and would not have a conversion performed.

E.g.:

operator+( a, b );  // conversions performed on a and b
a->operator+( b );  // conversion can only be performed on b
anon