When Not to Overload Operators

You should overload operators only when the meaning of the operator is clear and unambiguous. The arithmetic operators like + and * are meaningful when applied to numeric classes, such as complex numbers, but not to everything. For example, consider overloading the + operator for Date objects:

laterDate = myDate + yourDate; // Meaning?

It's anyone's guess what this statement means.

Many programmers overload the + operator for a String class to perform concatenation of two String objects. However, overloading relational operators for a String class might not be appropriate:

String myString( "John Smith" ),

yourString( "JOHN SMITH" );

if( myString == yourString ) // True or false?

// ...

A person reading this statement cannot tell whether the comparison being performed is case-sensitive or not. You could define a separate function to control case-sensitivity, but the combination might not be as clear as using named member functions.

Sometimes an overloaded operator clearly suggests a particular meaning to one programmer but suggests a different meaning to another programmer. For example, consider having a class Set, where each object represents a collection of objects. It would be useful to be able to calculate the “union” of two sets, that is, the set that contains the contents of both without duplications. Someone might pick the && operator for this purpose. For example:

ourSet = mySet && yourSet; // Clearly union

The programmer who wrote this statement might think it clearly indicates that ourSet contains everything in mySet combined with everything in yourSet. But another programmer might use the operator in the following way:

// Intersection or union?

targetSet = wealthySet && unmarriedSet;

Does targetSet contains everyone who is both wealthy and unmarried? Or does it contains everyone who is either wealthy, or unmarried?

Too many overloaded operators, or even a few badly chosen operators, can make your programs exceedingly difficult to read. Don't use overloaded operators simply to make it easier for you to type in your programs. Other programmers may have to maintain your programs later on, and it's much more important that they be able to understand your code. Accordingly, choose your overloaded operators with great care, and use them sparingly.

Since numeric classes are usually the best candidates for operator overloading, let's consider how to overload arithmetic operators for such a class.