All Topics  
Operator overloading

 

   Email Print
   Bookmark   Link






 

Operator overloading



 
 
In computer programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
, operator 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....
) is a specific case of polymorphism in which some or all of operator
Operator (programming)

Programming languages generally support a set of operators that are similar to operator. A language may contain a fixed number of built-in operators or it may allow the creation of programmer-defined operators ....
s like +, =, or have different implementations depending on the types of their arguments. Sometimes the overloadings are defined by the language; sometimes the programmer can implement support for new types.

Operator overloading is useful because it allows the developer to program using notation closer to the target domain and allows user types to look like types built into the language.






Discussion
Ask a question about 'Operator overloading'
Start a new discussion about 'Operator overloading'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computer programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
, operator 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....
) is a specific case of polymorphism in which some or all of operator
Operator (programming)

Programming languages generally support a set of operators that are similar to operator. A language may contain a fixed number of built-in operators or it may allow the creation of programmer-defined operators ....
s like +, =, or

have different implementations depending on the types of their arguments. Sometimes the overloadings are defined by the language; sometimes the programmer can implement support for new types.

Operator overloading is useful because it allows the developer to program using notation closer to the target domain and allows user types to look like 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
Precedence

Precedence is a simple ordering, based on either importance or sequence; it may refer to one of the following:* Message precedence of military communications traffic...
 than '+', this is effectively a more concise way of writing:

add (a, multiply (b,c))

However, in C++ templates or even C macro
Macro

A macro in computer science is a rule or pattern that specifies how a certain input sequence should be mapped to an output sequence according to a defined procedure....
s, operator overloading is needed in writing down generic, primitive operations such as summing elements when implementing a vector template. The only way to write primitive addition is a + b and this works for all types of elements only because of its overloading. (Actually, in C++ one could define an overloaded function add to use instead, but not in C.)

A more general variant of operator overloading, called expression reduction, allows expressions containing one or multiple operators to be reduced to a single function call. The expression above could be reduced to:

operator_add_and_multiply_integers(a, b, c)

Example

In this case, the addition operator is overloaded to allow addition on a user-defined type "Date" (in C++):

Date Dateoperator+(Date lhs, Date rhs)

Addition is a binary
Binary operation

In mathematics, a binary operation is a calculation involving two operands, in other words, an operation whose arity is two. Binary operations can be accomplished using either a binary function or binary operator....
 operation, which means it has a left and right operand
Operand

An operand is one of the inputs of an operator in mathematics. The following arithmetic expression shows an example of operators and operands:...
. In C++, the temp object in this case is the left operand and the arguments being passed are the right operands. Note that a unary
Unary operation

In mathematics, a unary operation is an operation with only one operand, i.e. an operation with a single input, or in other words, a function of one variable ....
 operator would receive no arguments since it doesn't have any operands.

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 general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
'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.

Changing the semantics can even happen by accident, as a common pitfall in C++ operator overloading is confusion between the arithmetic operators and assignment
Assignment (computer science)

In computer science the assignment statement sets or re-sets the Value stored in the storage location denoted by a variable name. In most imperative programming computer programming languages the assignment statement is one of the basic Statement s....
 operators: Beginners frequently overload the addition (+) operator but give it the semantics of the assignment by addition (+=) operator, resulting in simple expressions like a + b unexpectedly modifying a.

The common reply to this criticism, given by programmers who favor operator overloading, 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 expected or unintentionally assumed. For example the commutativity of + (i.e. that a + b

b + a) does not always apply; for example when the operands are strings (i.e. "school" + "bag" is different from "bag" + "school"). A typical counter to this argument comes directly from mathematics: While + is commutative on Integers (and in general any Ring), it is not commutative for other "types" of variable. It can be further noted that + is not even commutative on floating point values in practice due to rounding errors.

Operators are overloaded so that the objects behave as primitive types. New operators cannot be created, only the functionality of existing operators on objects can be modified; at least in C++.

A particular problem from the aspect of performance, is that operator overloading can describe nothing about the relationships between the operators. For instance, it is the case that for an unsigned integer x, the expressions x * 4, x + x + x + x, and x << 2 are equivalent, and a compiler can use this equivalence to select the most efficient for every occurrence of the expressions. In contrast, were x an object of a hypothetical Integer class, these expressions would necessarily be output verbatim. As a realistic example, the matrix expression A * B + C has optimization potential that cannot be realized with the straightforward multiply-then-add technique that is the result of overloaded * and + operators. Such optimization opportunities and more can be harnessed explicitly using techniques like expression templates
Expression templates

Expression templates is a C++ template metaprogramming technique in which Generic programming are used to represent part of an expression. Typically, the template itself represents a particular type of operation, while the parameters represent the operation to which the operation applies....
 in C++.

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 late 1970s at the University of Edinburgh, whose syntax is inspired by ISWIM....
  • Pico
    Pico programming language

    Pico is a programming language developed at the PROG lab at the Vrije Universiteit Brussel. The language was created to introduce the essentials of programming to non computer science students....
     
  • ALGOL 68
    ALGOL 68

    ALGOL 68 is an imperative programming computer programming programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously defined syntax and semantics....
  • Eiffel
    Eiffel (programming language)

    Eiffel is an International Organization for Standardization-standardized, object-oriented programming language designed to enable programmers to efficiently develop extensible, reusable, reliable software....
  • Fortran
    Fortran

    Fortran is a general-purpose programming language, procedural programming language, imperative programming language programming language that is especially suited to numerical analysis and scientific computing....
     
  • F#
  • Haskell
    Haskell (programming language)

    Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:...
     
  • Io
    Io (programming language)

    Io is a pure Object-oriented programming Computer programming Programming language inspired by Smalltalk, Self , Lua , Lisp , Act1, and NewtonScript....
  • Lisp
    Lisp programming language

    Lisp is a family of computer programming languages with a long history and a distinctive, fully parenthesized syntax. Originally specified in 1958, Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older....
     
  • Prolog
    Prolog

    Prolog is a logic programming language. It is a general purpose language often associated with artificial intelligence and computational linguistics....
  • Perl 6
    Perl 6

    Perl 6 is a planned major revision to the Perl programming language. It is a language specification which introduces elements of many modern and historical languages....
  • Scala
  • Smalltalk
    Smalltalk

    Smalltalk is an Object-oriented programming, Type system, reflection computer programming 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 learning, at PARC by Al...
  • Limited set
  • C
    C (programming language)

    C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
  • 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 ....
  • JavaScript
    JavaScript

    JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard....
  • Objective-C
    Objective-C

    Objective-C is a Reflection , Object-oriented programming programming language which adds Smalltalk-style message passing to C .Today it is used primarily on Mac OS X, iPhone OS, and GNUstep, three environments based on the OpenStep standard, and is the primary language used for the NEXTSTEP, OpenStep#OPENSTEP, and Cocoa application framew...
  • Pascal
    Pascal (programming language)

    Pascal is an influential imperative programming and Procedural programming 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 structure....
  • BASIC
    BASIC

    In computer programming, BASIC is a family of high-level programming languages. The Dartmouth BASIC was designed in 1964 by John George Kemeny and Thomas Eugene Kurtz at Dartmouth College in New Hampshire, United States to provide computer access to non-science students....
  • PHP
    PHP

    PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
  • Ada
    Ada (programming language)

    Ada is a structured programming, statically typed, Imperative programming, and Object-oriented programming high-level language computer programming programming language, extended from Pascal and other languages....
  • C++
    C++

    C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
  • C#
  • D
  • FreeBASIC
    FreeBASIC

    FreeBASIC is a free software/open source , 32-bit BASIC compiler for Microsoft Windows, protected-mode DOS , Linux, and Xbox.FreeBASIC allows a high level of support for Computer programs written for QBasic, by using the "QB" dialect....
  • Groovy
  • Lua
  • Object Pascal
    Object Pascal

    Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi....
     (Delphi, since 2005)
  • Perl
    Perl

    In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
  • Python
    Python (programming language)

    Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
  • Ruby
    Ruby (programming language)

    Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
  • Visual Basic 2005
    Visual Basic .NET

    Visual Basic , formerly called Visual Basic .NET , is an object-oriented programming computer language that can be viewed as an evolution of Microsoft Visual Basic implemented on the .NET Framework....


  • Notes:

    Timeline of operator overloading


    1960s

    The ALGOL 68
    ALGOL 68

    ALGOL 68 is an imperative programming computer programming programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously defined syntax and semantics....
     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; b) op ? = (bool a, b) bool: ( a | b | false ); c) op ¬ = (bool a) bool: ( a | false | true ); d) op = = (bool a, b) bool ? ( ¬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 programming, statically typed, Imperative programming, and Object-oriented programming high-level language computer programming programming language, extended from Pascal and other languages....
     supported overloading of operators from its inception with the publication of the Ada 83 language standard. However, the designers of the language consciously chose 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) have maintained the restriction to overloading of existing operators.

    C++
    C++

    C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
    's operator overloading was further refined from that of ALGOL 68
    ALGOL 68

    ALGOL 68 is an imperative programming computer programming programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously defined syntax and semantics....
    's.

    1990s

    Sun deliberately chooses not include operator overloading in the Java language.

    (cite: http://www.cafeaulait.org/javafaq.html#xtocid1902938)

    2001

    Microsoft includes operator overloading in C#.

    See also

    • Polymorphism (computer science)
    • Subroutine
      Subroutine

      In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....