- Operator overloading
-
Theories and practice of polymorphism - Double dispatch
- Multiple dispatch
- Operator overloading
- Polymorphism in computer science
- Polymorphism in OOP
- Subtyping
- Virtual function
- Single & dynamic dispatch
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by the language, the programmer, or both.
Operator overloading is claimed to be useful because it allows the developer to program using notation "closer to the target domain"[1] and allows user-defined types a similar level of syntactic support as types built into the language. It can easily be emulated using function calls; for an example, consider the integers a, b, c:
a + b * c
In a language that supports operator overloading, and assuming the '*' operator has higher precedence than '+', this is effectively a more concise way of writing:
add (a, multiply (b,c))
Contents
Examples
In this case, the addition operator is overloaded to allow addition on a user-defined type "Time" (in C++):
Time operator+(const Time& lhs, const Time& rhs) { Time temp = lhs; temp.seconds += lhs.seconds; if (temp.seconds >= 60) { temp.seconds -= 60; temp.minutes++; } temp.minutes += rhs.minutes; if (temp.minutes >= 60) { temp.minutes -= 60; temp.hours++; } temp.hours += rhs.hours; return temp; }
Addition is a binary operation, which means it has left and right operands. In C++, the arguments being passed are the operands, and the
temp
object is the returned value.The operation could also be defined as a class method, replacing
lhs
by the hiddenthis
argument; however this forces the left operand to be of typeTime
and supposesthis
to be a potentially modifiable lvalue:Time Time::operator+(const Time& rhs) const { Time temp = *this; /* Copy 'this' which is not to be modified */ temp.seconds += rhs.seconds; if (temp.seconds >= 60) { temp.seconds -= 60; temp.minutes++; } temp.minutes += rhs.minutes; if (temp.minutes >= 60) { temp.minutes -= 60; temp.hours++; } temp.hours += rhs.hours; return temp; }
Note that a unary operator defined as a class method would receive no apparent argument (it only works from
this
):bool Time::operator!() const { return ((hours == 0) && (minutes == 0) && (seconds == 0)); }
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 in general any real 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.Catalog
A classification of some common programming languages by whether their operators are overloadable by the programmer and whether the operators are limited to a predefined set.
Operators Not overloadable Overloadable New definable Limited set - Ada
- C++
- C#
- D
- FreeBASIC
- Groovy
- Lua
- Delphi (since 2005)
- Object Pascal (Free Pascal[6])
- PHP (using magic methods or ArrayAccess interface or Operator extension)
- Perl
- Python
- Ruby
- Visual Basic 2005
Timeline of operator overloading
1960s
The ALGOL 68 specification allowed operator overloading.[7]
Extract from the ALGOL 68 language specification (page 177) where the overloaded operators ¬, =, ≠ and abs are defined:
10.2.2. Operations on Boolean Operands a) op ∨ = (bool a, b) bool:( a | true | b ); b) op ∧ = (bool a, b) bool: ( a | b | false ); c) op ¬ = (bool a) bool: ( a | false | true ); d) op = = (bool a, b) bool:( a∧b ) ∨ ( ¬b∧¬a ); e) op ≠ = (bool a, b) bool: ¬(a=b); f) op abs = (bool a)int: ( a | 1 | 0 );
Note that no special declaration is required to overload an operator, and the programmer is free to create new operators.
1980s
Ada supports overloading of operators from its inception, with the publication of the Ada 83 language standard. However, the designers of the language choose not to permit the definition of new operators: only the existing operators in the language may be overloaded (by defining new functions with identifiers such as "+", "*", "and" etc.). Subsequent revisions of the language (in 1995 and 2005) maintain the restriction to overloading of existing operators.
C++'s operator overloading is further refined from that of ALGOL 68's.[8]
1990s
Sun chooses not to include operator overloading in the Java language.[9][10]
2001
Microsoft includes operator overloading in C#.
See also
- Function overloading
- Polymorphism (computer science)
- Subroutine
- Operator (programming)
- Operators in C and C++
References
- ^ "C++ FAQ Lite: What are the benefits of operator overloading?". June 2010. http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.2. Retrieved August 2010.
- ^ binary functions with a symbolic name can be called infix
- ^ introduced in Fortran 90
- ^ type classes instead of overloading
- ^ "Why does Go not support overloading of methods and operators?". http://golang.org/doc/go_faq.html#overloading. Retrieved 4 September 2011.
- ^ "Operator Overloading, Free Pascal Manual". http://www.freepascal.org/docs-html/ref/refse66.html#x162-17200012.1. Retrieved June 2011.
- ^ A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck and C.H.A. Koster, et al. (August 1968). "Report on the Algorithmic Language ALGOL 68, Section 10.2.2." (PDF). http://www.fh-jena.de/~kleine/history/languages/Algol68-Report.pdf. Retrieved April 2007.
- ^ Bjarne Stroustrup. "A History of C++: 1979−1991 - page 12" (PDF). http://www.research.att.com/~bs/hopl2.pdf. Retrieved April 2007.
- ^ [1]
- ^ [2]
Categories:- Operators (programming)
Wikimedia Foundation. 2010.