Operator Overloading - Criticisms

Criticisms

Operator overloading has often been criticized because it allows programmers to give operators completely different semantics depending on the types of their operands. For example the use of the << in C++'s:

a << 1

shifts the bits in the variable a left by 1 bit if a is of an integer type, but if a is an output stream then the above code will attempt to write a "1" to the stream. Because operator overloading allows the original programmer to change the usual semantics of an operator and to catch any subsequent programmers by surprise, it is usually considered good practice to use operator overloading with care.

The common reply to this criticism is that the same argument applies to function overloading as well. Furthermore, even in the absence of overloading, a programmer can define a function to do something totally different from what would be expected from its name. An issue that remains is that languages such as C++ provide a limited set of operator symbols, thus removing from programmers the option of choosing a more suitable operator symbol for their new operation.

Another, more subtle issue with operators is that certain rules from mathematics can be wrongly expected or unintentionally assumed. For example the commutativity of + (i.e. that a + b == b + a) does not always apply; an example of this occurs when the operands are strings, since + is commonly overloaded to perform a concatenation of strings (i.e. "school" + "bag" yields "schoolbag", which is different from "bag" + "school" yields "bagschool"). A typical counter to this argument comes directly from mathematics: While + is commutative on integers (and most generally any complex numbers), it is not commutative for other "types" of variable. It can be further noted that + is not even associative on floating point values in practice due to rounding errors. Another example: binary * (multiplication) is commutative for integers but not commutative in case of matrix multiplication.

Read more about this topic:  Operator Overloading

Famous quotes containing the word criticisms:

    The sway of alcohol over mankind is unquestionably due to its power to stimulate the mystical faculties of human nature, usually crushed to earth by the cold facts and dry criticisms of the sober hour. Sobriety diminishes, discriminates, and says no; drunkenness expands, unites, and says yes.
    William James (1842–1910)

    I have no concern with any economic criticisms of the communist system; I cannot enquire into whether the abolition of private property is expedient or advantageous. But I am able to recognize that the psychological premises on which the system is based are an untenable illusion. In abolishing private property we deprive the human love of aggression of one of its instruments ... but we have in no way altered the differences in power and influence which are misused by aggressiveness.
    Sigmund Freud (1856–1939)