[   ^ to index...   |   <-- previous   |   next -->   ]

The real story about user-defined overloaded operators

There are two ways to overload an operator. One, which we've already seen, is to define a member function for a class. In this case, the operator will apply when the left-hand argument is an instance of the class:

class Foo { // ... Foo& operator+=(int i); }; Foo f; f += 4; // will invoke operator given above

The other way is to define a free-floating function that takes two arguments. This operator will apply when the arguments are of the same types as the two formal parameters of the operator:

// Basically equivalent to the above class Foo { /* whatever */ }; Foo& operator+=(Foo& left, int right);

However, notice that since the latter version is not a member function of Foo, it will not have access to any of Foo's private or protected members. Therefore, it is common to declare free-floating operators to be friend functions of the class(es) to which they apply.

For reasons of sanity, at least one argument for any user-defined operator must be a user-defined type (you cannot overload "int operator+(int, int)").

How many operators can I overload?

Virtually all of them. Almost any symbol in C++ except curly braces, scope resolution, and member selection can be overloaded. Furthermore, you can define a conversion operator between any two user-defined types.

How many operators should I overload?

Be sparing. It is easy to define essentially a whole other language within C++ by using overloaded operators. Your fellow C++ coders do not want to learn your language; they just want to read your code and understand it. Also, as previously mentioned, it is also possible to introduce ambiguities by using type conversion operators and overloaded operators in concert. Finally, inheritance with virtual functions and operator overloading have "interesting" feature interactions (if you don't believe me, go home and write a small class heirarchy using virtual overloaded operators).

Therefore, impose strict discipline on how and where you use overloaded operators. Often it's appropriate to start out using member functions such as addAmount() instead of operator+=(), and augment the class with an overloaded operator if the operation proves popular.


Last modified: Mon Jul 31 15:41:47 PDT 2000