The binary operators =
(assignment), []
(array subscription), ->
(member access), as well as the n-ary ()
(function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.
Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators <<
and >>
, whose left operands are stream classes from the standard library which you cannot change.
For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:
Of course, as with all rules of thumb, there are exceptions. If you have a type
enum Month {Jan, Feb, ..., Nov, Dec}
and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<()
for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.
(However, if you make an exception, do not forget the issue of const
-ness for the operand that, for member functions, becomes the implicit this
argument. If the operator as a non-member function would take its left-most argument as a const
reference, the same operator as a member function needs to have a const
at the end to make *this
a const
reference.)
Continue to Common operators to overload.