Operator overloading
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, operator overloading, sometimes termed ''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 a
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
, a
programmer A programmer, computer programmer or coder is an author of computer source code someone with skill in computer programming. The professional titles Software development, ''software developer'' and Software engineering, ''software engineer' ...
, or both.


Rationale

Operator overloading is
syntactic sugar In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
, and is used because it allows programming using notation nearer to the target domain and allows user-defined types a similar level of syntactic support as types built into a language. It is common, for example, in scientific computing, where it allows computing representations of mathematical objects to be manipulated with the same syntax as on paper. Operator overloading does not change the expressive power of a language (with functions), as it can be emulated using function calls. For example, consider variables , and of some user-defined type, such as matrices: In a language that supports operator overloading, and with the usual assumption that the operator has higher precedence than the operator, this is a concise way of writing: However, the former syntax reflects common mathematical usage.


Examples

In this case, the addition operator is overloaded to allow addition on a user-defined type in C++: Time operator+(const Time& lhs, const Time& rhs) Addition is a
binary operation In mathematics, a binary operation or dyadic operation is a rule for combining two elements (called operands) to produce another element. More formally, a binary operation is an operation of arity two. More specifically, a binary operation ...
, which means it has two
operand In mathematics, an operand is the object of a mathematical operation, i.e., it is the object or quantity that is operated on. Unknown operands in equalities of expressions can be found by equation solving. Example The following arithmetic expres ...
s. In C++, the arguments being passed are the operands, and the object is the returned value. The operation could also be defined as a class method, replacing by the hidden argument; However, this forces the left operand to be of type : // The "const" right before the opening curly brace means that , this, is not modified. Time Time::operator+(const Time& rhs) const Note that a unary operator defined as a class method would receive no apparent argument (it only works from ): bool Time::operator!() const The less-than (<) operator is often overloaded to sort a structure or class: class Pair ; Like with the previous examples, in the last example operator overloading is done within the class. In C++, after overloading the less-than operator (<), standard sorting functions can be used to sort some classes.


Criticisms

Operator overloading has often been criticized because it allows programmers to reassign the semantics of operators depending on the types of their operands. For example, the use of the operator in C++ a << b shifts the bits in the variable left by bits if and are of an integer type, but if is an output stream then the above code will attempt to write a 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 considered good practice to use operator overloading with care (the creators of
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
decided not to use this feature, although not necessarily for this reason). Another, more subtle, issue with operators is that certain rules from mathematics can be wrongly expected or unintentionally assumed. For example, the
commutativity In mathematics, a binary operation is commutative if changing the order of the operands does not change the result. It is a fundamental property of many binary operations, and many mathematical proofs depend on it. Perhaps most familiar as a p ...
of + (i.e. that ) 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. yields , while yields ). A typical counter to this argument comes directly from mathematics: While + is commutative on integers (and more generally any complex number), it is not commutative for other "types" of variables. In practice, + is not even always
associative In mathematics, the associative property is a property of some binary operations that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a valid rule of replacement for express ...
, for example with floating-point values due to rounding errors. Another example: In mathematics, multiplication is commutative for real and complex numbers but not commutative in
matrix multiplication In mathematics, specifically in linear algebra, matrix multiplication is a binary operation that produces a matrix (mathematics), matrix from two matrices. For matrix multiplication, the number of columns in the first matrix must be equal to the n ...
.


Catalog

A classification of some common programming languages is made according to whether their operators are overloadable by the programmer and whether the operators are limited to a predefined set.


Timeline of operator overloading


1960s

The
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language member of the ALGOL family that was conceived as a successor to the ALGOL 60 language, designed with the goal of a much wider scope of application and ...
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 needed to ''overload'' an operator, and the programmer is free to create new operators. For dyadic operators their priority compared to other operators can be set: prio max = 9; op max = (int a, b) int: ( a>b , a , b ); op ++ = ( ref int a ) int: ( a +:= 1 );


1980s

Ada supports overloading of operators from its inception, with the publication of the Ada 83 language standard. However, the language designers chose to preclude the definition of new operators. Only extant operators in the language may be overloaded, by defining new functions with identifiers such as "+", "*", "&" etc. Subsequent revisions of the language (in 1995 and 2005) maintain the restriction to overloading of extant operators. In C++, operator overloading is more refined than in
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language member of the ALGOL family that was conceived as a successor to the ALGOL 60 language, designed with the goal of a much wider scope of application and ...
.


1990s

Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
language designers at
Sun Microsystems Sun Microsystems, Inc., often known as Sun for short, was an American technology company that existed from 1982 to 2010 which developed and sold computers, computer components, software, and information technology services. Sun contributed sig ...
chose to omit overloading. Python allows operator overloading through the implementation of methods with special names. For example, the addition (+) operator can be overloaded by implementing the method .
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
allows operator overloading as syntactic sugar for simple method calls. Lua allows operator overloading as syntactic sugar for method calls with the added feature that if the first operand doesn't define that operator, the method for the second operand will be used.


2000s

Microsoft added operator overloading to C# in 2001 and to Visual Basic .NET in 2003. Scala treats all operators as methods and thus allows operator overloading by proxy. In Raku, the definition of all operators is delegated to lexical functions, and so, using function definitions, operators can be overloaded or new operators added. For example, the function defined in the
Rakudo Rakudo is a Raku compiler targeting MoarVM, and the Java Virtual Machine, that implements the Raku specification. It is currently the only major Raku compiler in active development. Originally developed within the Parrot Parrots (Psittacif ...
source for incrementing a Date object with "+" is: multi infix:<+>(Date:D $d, Int:D $x) Since "multi" was used, the function gets added to the list of multidispatch candidates, and "+" is only overloaded for the case where the type constraints in the function signature are met. While the capacity for overloading includes +, *, >=, the postfix and term i, and so on, it also allows for overloading various brace operators: " ''x, y''", "x ''y''", "x", and "x(y)". Kotlin has supported operator overloading since its creation.


See also

* Function overloading *
Polymorphism (computer science) In programming language theory and type theory, polymorphism is the use of one symbol to represent multiple different types.: "Polymorphic types are types whose operations are applicable to values of more than one type." In object-oriented progr ...
*
Subroutine In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-defined interface and behavior and can be invoked multiple times. Callable units provide a ...
* Operator (programming) * Operators in C and C++ *
Mutator method In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable. They are also ...
*
Indexer (programming) In object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called ...
*
Property (programming) A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method. The syntax for reading and writing of properties is like for fields, but ...


References

{{DEFAULTSORT:Operator Overloading Articles with example ALGOL 68 code Operators (programming)