Operator overloading
Encyclopedia
In object oriented computer programming
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...

, operator
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

 overloading
—less commonly known as operator ad-hoc polymorphism
Type polymorphism
In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions...

—is a specific case of polymorphism, where different operator
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

s have different implementations depending on their arguments. Operator overloading is generally defined by the language, the programmer, or both.

Operator
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

 overloading is claimed to be useful because it allows the developer to program using notation "closer to the target domain" 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
Order of operations
In mathematics and computer programming, the order of operations is a rule used to clarify unambiguously which procedures should be performed first in a given mathematical expression....

 than '+', this is effectively a more concise way of writing:

add (a, multiply (b,c))

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 += 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;
}


Addition is a binary operation
Binary operation
In mathematics, a binary operation is a calculation involving two operands, in other words, an operation whose arity is two. Examples include the familiar arithmetic operations of addition, subtraction, multiplication and division....

, 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 hidden this argument; however this forces the left operand to be of type Time and supposes this 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
Unary operation
In mathematics, a unary operation is an operation with only one operand, i.e. a single input. Specifically, it is a functionf:\ A\to Awhere A is a set. In this case f is called a unary operation on A....

 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++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

'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
Binary operation
In mathematics, a binary operation is a calculation involving two operands, in other words, an operation whose arity is two. Examples include the familiar arithmetic operations of addition, subtraction, multiplication and division....

 * (multiplication) is commutative for integers but not commutative in case of matrix multiplication
Matrix multiplication
In mathematics, matrix multiplication is a binary operation that takes a pair of matrices, and produces another matrix. If A is an n-by-m matrix and B is an m-by-p matrix, the result AB of their multiplication is an n-by-p matrix defined only if the number of columns m of the left matrix A is the...

.

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
  • ML
    ML programming language
    ML is a general-purpose functional programming language developed by Robin Milner and others in the early 1970s at the University of Edinburgh, whose syntax is inspired by ISWIM...

  • Pico
    Pico programming language
    Pico is a programming language developed at the Software Languages Lab at Vrije Universiteit Brussel. The language was created to introduce the essentials of programming to non-computer science students....

  • Prolog
    Prolog
    Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is declarative: the program logic is expressed in terms of...

  • ALGOL 68
  • Eiffel
    Eiffel (programming language)
    Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...

  • Fortran
    Fortran
    Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...

  • F#
  • Haskell
    Haskell (programming language)
    Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

  • Io
    Io (programming language)
    Io is a pure object-oriented programming language inspired by Smalltalk, Self, Lua, Lisp, Act1, and NewtonScript. Io has a prototype-based object model similar to the ones in Self and NewtonScript, eliminating the distinction between instance and class. Like Smalltalk, everything is an object and...

  • Perl 6
    Perl 6
    Perl 6 is a major revision to the Perl programming language. It is still in development, as a specification from which several interpreter and compiler implementations are being written. It is introducing elements of many modern and historical languages. Perl 6 is intended to have many...

  • R
    R (programming language)
    R is a programming language and software environment for statistical computing and graphics. The R language is widely used among statisticians for developing statistical software, and R is widely used for statistical software development and data analysis....

  • Scala
  • Smalltalk
    Smalltalk
    Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

  • Limited set
  • C
    C (programming language)
    C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

  • Go
    Go (programming language)
    Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being...

  • Java
    Java (programming language)
    Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

  • JavaScript
    JavaScript
    JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

  • Modula-2
    Modula-2
    Modula-2 is a computer programming language designed and developed between 1977 and 1980 by Niklaus Wirth at ETH Zurich as a revision of Pascal to serve as the sole programming language for the operating system and application software for the personal workstation Lilith...

  • Objective-C
    Objective-C
    Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

  • Pascal
    Pascal (programming language)
    Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...

  • BASIC
    BASIC
    BASIC is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use - the name is an acronym from Beginner's All-purpose Symbolic Instruction Code....

  • Ada
    Ada (programming language)
    Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

  • C++
    C++
    C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

  • C#
  • D
  • FreeBASIC
    FreeBASIC
    FreeBASIC is a free/open source , 32-bit BASIC compiler for Microsoft Windows, protected-mode DOS , Linux, FreeBSD and Xbox....

  • Groovy
  • Lua
  • Delphi (since 2005)
  • Object Pascal
    Object Pascal
    Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...

     (Free Pascal
    Free Pascal
    Free Pascal Compiler is a free Pascal and Object Pascal compiler.In addition to its own Object Pascal dialect, Free Pascal supports, to varying degrees, the dialects of several other compilers, including those of Turbo Pascal, Delphi, and some historical Macintosh compilers...

    )
  • PHP
    PHP
    PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

     (using magic methods or ArrayAccess interface or Operator extension)
  • Perl
    Perl
    Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

  • Python
    Python (programming language)
    Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

  • Ruby
    Ruby (programming language)
    Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

  • Visual Basic 2005
    Visual Basic .NET
    Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...


  • 1960s

    The ALGOL 68
    ALGOL 68
    ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...

     specification allowed operator overloading.

    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
    Ada (programming language)
    Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

     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++
    C++
    C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

    's operator overloading is further refined from that of ALGOL 68
    ALGOL 68
    ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...

    's.

    See also

    • Function overloading
    • Polymorphism (computer science)
    • Subroutine
      Subroutine
      In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

    • Operator (programming)
      Operator (programming)
      Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

    • Operators in C and C++
      Operators in C and C++
      This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the fourth column "Included in C", dictates whether an operator is also present in C...

    The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
     
    x
    OK