Operator Overloading
Do not overload operators except in rare, special circumstances.Definition:
A class can define that operators such as +
and
/
operate on the class as if it were a built-in
type.
Pros:
Can make code appear more intuitive because a class will
behave in the same way as built-in types (such as
int
). Overloaded operators are more playful
names for functions that are less-colorfully named, such as
Equals()
or Add()
. For some
template functions to work correctly, you may need to define
operators.
Cons: While operator overloading can make code more intuitive, it has several drawbacks:
- It can fool our intuition into thinking that expensive operations are cheap, built-in operations.
- It is much harder to find the call sites for overloaded
operators. Searching for
Equals()
is much easier than searching for relevant invocations of==
. - Some operators work on pointers too, making it easy to
introduce bugs.
Foo + 4
may do one thing, while&Foo + 4
does something totally different. The compiler does not complain for either of these, making this very hard to debug.
operator&
.
Decision:
operator=
), in particular, is insidious and
should be avoided. You can define functions like
Equals()
and CopyFrom()
if you need
them.
However, there may be rare cases where you need to overload
an operator to interoperate with templates or "standard" C++
classes (such as operator<<(ostream&, const
T&)
for logging). These are acceptable if fully
justified, but you should try to avoid these whenever
possible. In particular, do not overload operator==
or operator<
just so that your class can be
used as a key in an STL container; instead, you should
create equality and comparison functor types when declaring
the container.
operator==
, and you may do so in these cases,
provided you document why.