Continued . . .
Operator overloading offers advantages not only over C, but also over newer object-oriented languages as well. In these languages, we face the same problem. How do we make a sort that works on fundamental types and programmer-defined types? With an object-oriented structure, we can create an interface with a comparison function that all sortable types inherit. Then we can wrap native types, like double, with a class that inherits our interface, say Double. The technique of wrapping fundamental types in objects is often refered to as boxing. Converting from the wrapped type back to the fundamental type is called unboxing.
With this technique, a single sort can work on all of our types. However, our data types suffer the memory inefficiency of the wrapping object and speed inefficiency of conversion from boxing and unboxing. Additionally, the conversions back and forth between fundamental and wrapped types is cumbersome. So, we see that templates and operator overloading offer advantages over other languages, particular in terms of speed and memory usage.
For programmers who work with numerical algorithms, operator overloading offers still more benefits. We can overload arithmetical operators to make object conform to the mathematical structures from abstract algebra like fields, rings, etc. For example, if we create a class for complex numbers or matrices, we might want to overload “+”, “*”, etc. It is important to use these operators properly. In this context, operator overloading can be very powerful.
One of the most common uses, and abuses, of operator overloading is the use of “+” to concatenate strings. Unfortunately, this usage is common in many languages and has even been used in the C++ STL string class. The STL has an elegant architecture to it, but this usage only seems to add confusion and further the idea of operator overloading as “syntactic sugar.” My problem with using “+” in string classes is that the usage does not conform to the intended mathematical meaning of the symbol.
Overloading a mathematical operator, like “+”, has many legitimate purposes in programming classes like quaternions, Taylor series, matrices, finite fields, complex numbers, vectors, polynomials, etc. If you are not working with mathematical types, overloading mathematical operators is probably a mistake.