Operator overloading is a computer programming language construct found in object oriented languages such as C++ and C#. It is intended to make user-defined objects and methods be just as useful and convenient as the built-in ones.1

It is generally a bad idea.

All powerful programming language features are potentially dangerous in the wrong hands. Operator overloading, however, offers one of the most unfavourable power to danger ratios: not very powerful, and quite dangerous with it.

Operator overloading is a piece of syntactic sugar that allows you, given objects A, B and C, instead of writing A.Sum(B, C);, to code A = B + C;, just as if they were of built-in types, not user-defined object types. The compiler or runtime then searches for an appropriate operator overload in order to translate the latter into the former. Aside from mathematical operators, type casts can usually also be overridden, e.g. to automatically generate a string describing your object, or an integer value from it.

Since the languages that have operator overloading are generally strongly typed2, it does not actually allow you to write generic code that can also accept integers, unless the code is inside a template or the like.

Operator overloading offers the promise of convenience, but doesn't really add to the language. Anything that can be done with operator overloading can be done without it, in a more explicit format.

Though using operator overloads instead of method calls is aimed at increasing readability, they are easy to misread. Operator overloading introduces hidden code. Reading code such as A = B;, it's not obvious that an operator has been overridden somewhere else in the code to convert B's type to A's, and has been triggered by this line. You don't know if the person who coded this, for instance accounted for the possibility of B being null, or equal to A. You may get an error, and go looking for it, but the error is well hidden.

Overloading mathematical operators should be strongly avoided unless you happen to be coding a class that is a mathematical entity, which actually has mathematical operators defined on it, such as a class for a matrix, vector or complex number. This is not very common.


1) Thanks to jrn for pointing out the idea behind operator overloading.

2) The weakly typed Perl 6 being an exception. In perl 6, you can also create your own operators. This means that you don't have to re-use mathematical operators for obscure purposes. Oh no, your code can be rendered total opaque by assigning arbitrary meaning to random punctuation.

cjeris points out that in the LISP family of languages, particularly in CLOS, there is no need for operator overloading, as the language syntax makes it clear that the distinction between operator and method is an illusion. An addition operator would be used like (+ A B), and an addition method would be used like (+ A B).