Operator overloading: Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>Adius
Add Julia to operator overloading table
 
imported>Derek farn
Shorten long list to more well known languages
Line 23: Line 23:
<syntaxhighlight lang=Cpp>
<syntaxhighlight lang=Cpp>
Time operator+(const Time& lhs, const Time& rhs) {
Time operator+(const Time& lhs, const Time& rhs) {
  Time temp = lhs;
    Time temp = lhs;
  temp.seconds += rhs.seconds;
    temp.seconds += rhs.seconds;
  temp.minutes += temp.seconds / 60;
    temp.minutes += temp.seconds / 60;
  temp.seconds %= 60;
    temp.seconds %= 60;
  temp.minutes += rhs.minutes;
    temp.minutes += rhs.minutes;
  temp.hours += temp.minutes / 60;
    temp.hours += temp.minutes / 60;
  temp.minutes %= 60;
    temp.minutes %= 60;
  temp.hours += rhs.hours;
    temp.hours += rhs.hours;
  return temp;
    return temp;
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 40: Line 40:


<syntaxhighlight lang=Cpp>
<syntaxhighlight lang=Cpp>
// The "const" right before the opening curly brace means that |this| is not modified.
// The "const" right before the opening curly brace means that `this` is not modified.
Time Time::operator+(const Time& rhs) const {
Time Time::operator+(const Time& rhs) const {
  Time temp = *this;  // |this| should not be modified, so make a copy.
    Time temp = *this;  // `this` should not be modified, so make a copy.
  temp.seconds += rhs.seconds;
    temp.seconds += rhs.seconds;
  temp.minutes += temp.seconds / 60;
    temp.minutes += temp.seconds / 60;
  temp.seconds %= 60;
    temp.seconds %= 60;
  temp.minutes += rhs.minutes;
    temp.minutes += rhs.minutes;
  temp.hours += temp.minutes / 60;
    temp.hours += temp.minutes / 60;
  temp.minutes %= 60;
    temp.minutes %= 60;
  temp.hours += rhs.hours;
    temp.hours += rhs.hours;
  return temp;
    return temp;
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 58: Line 58:
<syntaxhighlight lang=Cpp>
<syntaxhighlight lang=Cpp>
bool Time::operator!() const {
bool Time::operator!() const {
  return hours == 0 && minutes == 0 && seconds == 0;
    return hours == 0 && minutes == 0 && seconds == 0;
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 65: Line 65:


<syntaxhighlight lang=Cpp>
<syntaxhighlight lang=Cpp>
class Pair {
class IntegerPair {
public:
private:
  bool operator<(const Pair& p) const {
    int x;
    if (x_ == p.x_) {
    int y;
      return y_ < p.y_;
public:
    explicit IntegerPair(int x = 0, int y = 0):
        x{x}, y{y} {}
 
    bool operator<(const IntegerPair& p) const {
        if (x == p.x) {
            return y < p.y;
        }
        return x < p.x;
     }
     }
    return x_ < p.x_;
};
  }
</syntaxhighlight>


private:
Like with the previous examples, in the last example operator overloading is done within the class. In C++, after overloading the less-than operator (<code>operator<</code>), [[sort (C++)|standard sorting functions]] can be used to sort some classes.
  int x_;
 
  int y_;
Starting in [[C++20]] with the introduction of the [[three-way comparison]] operator (<code>operator<=></code>), all the order operators can be defined by just defining that operator. The three-way comparison operator exists in many languages, including [[C++]], [[Python (programming language)|Python]], [[Rust (programming language)|Rust]], [[Swift (programming language)|Swift]], and [[PHP]]. Other languages, such as [[Java (programming language)|Java]] and [[C Sharp (programming language)|C#]] instead use a method <code>Comparable.compareTo()</code>.
<syntaxhighlight lang=Cpp>
import std;
 
using std::strong_ordering;
 
class IntegerPair {
private:
    int x;
    int y;
public:
    explicit IntegerPair(int x = 0, int y = 0):
        x{x}, y{y} {}
 
    // can be auto-generated with = default;
    strong_ordering operator<(const IntegerPair& p) const {
        if (strong_ordering cmp = x <=> p.x; cmp != strong_ordering::equal) {
            return cmp;
        }
        return y <=> p.y;
    }
};
};
</syntaxhighlight>
</syntaxhighlight>
Like with the previous examples, in the last example operator overloading is done within the class. In C++, after overloading the less-than operator (<), [[sort (C++)|standard sorting functions]] can be used to sort some classes.


==Criticisms==
==Criticisms==
Line 99: Line 125:
| <!-- "Not overloadable" and "New operators definable" -->
| <!-- "Not overloadable" and "New operators definable" -->
*[[ML (programming language)|ML]]
*[[ML (programming language)|ML]]
*[[Pico (programming language)|Pico]]<ref>Binary functions with a symbolic name can be called infix.</ref>
*[[Prolog]]<ref>{{cite web |url=https://www.swi-prolog.org/pldoc/man?predicate=op/3 |title=Predicate op/3}}</ref>
*[[Prolog]]<ref>{{cite web |url=https://www.swi-prolog.org/pldoc/man?predicate=op/3 |title=Predicate op/3}}</ref>
|<!-- "Overloadable" and "New operators definable" -->
|<!-- "Overloadable" and "New operators definable" -->
Line 105: Line 130:
*[[Clojure]]
*[[Clojure]]
*[[Eiffel (programming language)|Eiffel]]<ref>{{Cite web|title=Bertrand Meyer: Basic Eiffel language mechanisms|url=http://se.ethz.ch/~meyer/publications/online/eiffel/basic.html|access-date=2021-04-07|website=se.ethz.ch}}</ref>
*[[Eiffel (programming language)|Eiffel]]<ref>{{Cite web|title=Bertrand Meyer: Basic Eiffel language mechanisms|url=http://se.ethz.ch/~meyer/publications/online/eiffel/basic.html|access-date=2021-04-07|website=se.ethz.ch}}</ref>
*[[Fortran]]<ref>{{Cite web|title=Operator functions in F90|url=http://www.mathcs.emory.edu/~cheung/Courses/561/Syllabus/6-Fortran/operators.html|access-date=2021-04-07|website=www.mathcs.emory.edu}}</ref><ref>Introduced in Fortran 90.</ref>
*[[Fortran]]<ref>{{Cite web|title=Operator functions in F90|url=http://www.mathcs.emory.edu/~cheung/Courses/561/Syllabus/6-Fortran/operators.html|access-date=2021-04-07|website=www.mathcs.emory.edu|archive-date=11 August 2021|archive-url=https://web.archive.org/web/20210811232057/http://www.mathcs.emory.edu/~cheung/Courses/561/Syllabus/6-Fortran/operators.html|url-status=dead}}</ref><ref>Introduced in Fortran 90.</ref>
*[[Futhark (programming language)|Futhark]]<ref>{{Cite web|title=3. Language Reference — Futhark 0.19.0 documentation|url=https://futhark.readthedocs.io/en/latest/language-reference.html|access-date=2020-10-10|website=futhark.readthedocs.io}}</ref>
*[[F Sharp (programming language)|F#]]<ref name="Smith2012">{{cite book |last=Smith |first=Chris |title=Programming F# 3.0: A Comprehensive Guide for Writing Simple Code to Solve Complex Problems |url=https://books.google.com/books?id=e0Wl6id4unQC&q=%22operator+overloading%22 |date=9 October 2012 |publisher=O'Reilly Media, Inc. |isbn=978-1-4493-2604-3}}</ref>
*[[F Sharp (programming language)|F#]]<ref name="Smith2012">{{cite book |last=Smith |first=Chris |title=Programming F# 3.0: A Comprehensive Guide for Writing Simple Code to Solve Complex Problems |url=https://books.google.com/books?id=e0Wl6id4unQC&q=%22operator+overloading%22 |date=9 October 2012 |publisher=O'Reilly Media, Inc. |isbn=978-1-4493-2604-3}}</ref>
*[[Haskell (programming language)|Haskell]]<ref>[[Type class]]es instead of overloading.</ref>
*[[Haskell (programming language)|Haskell]]<ref>[[Type class]]es instead of overloading.</ref>
*[[Io (programming language)|Io]]<ref>{{Cite web|title=io guide|url=https://iolanguage.org/guide/guide.html#Syntax-Operators|access-date=2021-04-07|website=iolanguage.org}}</ref>
*[[Julia (programming language)|Julia]]<ref>{{Cite web|title=Operator Overloading in Julia|url=https://www.geeksforgeeks.org/operator-overloading-in-julia/|access-date=2025-03-14
*[[Julia (programming language)|Julia]]<ref>{{Cite web|title=Operator Overloading in Julia|url=https://www.geeksforgeeks.org/operator-overloading-in-julia/|access-date=2025-03-14
|website=geeksforgeeks.org}}</ref>
|website=geeksforgeeks.org}}</ref>
*[[Nim (programming language)|Nim]]<ref>{{cite web|title=Operators|url=https://nim-lang.github.io/Nim/tut1.html#procedures-operators}}</ref>
*[[R (programming language)|R]]<ref>{{Cite web|title=Operators - R in a Nutshell, 2nd Edition [Book]|url=https://www.oreilly.com/library/view/r-in-a/9781449358204/ch06s02.html|access-date=2021-04-07|website=www.oreilly.com|language=en}}</ref>
*[[R (programming language)|R]]<ref>{{Cite web|title=Operators - R in a Nutshell, 2nd Edition [Book]|url=https://www.oreilly.com/library/view/r-in-a/9781449358204/ch06s02.html|access-date=2021-04-07|website=www.oreilly.com|language=en}}</ref>
*[[Raku (programming language)|Raku]]<ref>{{cite web |url=https://docs.raku.org/language/optut |title=Creating operators}}</ref>
*[[Scala (programming language)|Scala]]<ref>{{cite web |url=https://docs.scala-lang.org/tour/operators.html |website=Tour of Scala |title=Operators}}</ref>
*[[Scala (programming language)|Scala]]<ref>{{cite web |url=https://docs.scala-lang.org/tour/operators.html |website=Tour of Scala |title=Operators}}</ref>
*[[Seed7]]<ref>{{Cite web|title=Seed7 Manual: Structured syntax definition|url=http://seed7.sourceforge.net/manual/syntax.htm|access-date=2020-09-29|website=seed7.sourceforge.net}}</ref>
*[[Smalltalk]]<ref name="Hunt2012">{{cite book |last=Hunt |first=John |title=Smalltalk and Object Orientation: An Introduction |url=https://books.google.com/books?id=BiDUBwAAQBAJ&q=overloading+operators |date=6 December 2012 |publisher=Springer Science & Business Media |isbn=978-1-4471-0961-7}}</ref>
*[[Smalltalk]]<ref name="Hunt2012">{{cite book |last=Hunt |first=John |title=Smalltalk and Object Orientation: An Introduction |url=https://books.google.com/books?id=BiDUBwAAQBAJ&q=overloading+operators |date=6 December 2012 |publisher=Springer Science & Business Media |isbn=978-1-4471-0961-7}}</ref>
*[[Swift (programming language)|Swift]]<ref>{{cite web |url=https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html |title=Swift: Advanced Operators}}</ref>
*[[Swift (programming language)|Swift]]<ref>{{cite web |url=https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html |title=Swift: Advanced Operators}}</ref>
Line 136: Line 156:
*[[C Sharp (programming language)|C#]]<ref name="DraytonAlbahari2003">{{cite book |last1=Drayton |first1=Peter |last2=Albahari |first2=Ben |last3=Neward |first3=Ted |title=C# in a Nutshell |url=https://books.google.com/books?id=bG_Aqb6iOUYC&q=%22operator+overloading%22 |year=2003 |publisher=O'Reilly Media, Inc. |isbn=978-0-596-00526-9}}</ref>
*[[C Sharp (programming language)|C#]]<ref name="DraytonAlbahari2003">{{cite book |last1=Drayton |first1=Peter |last2=Albahari |first2=Ben |last3=Neward |first3=Ted |title=C# in a Nutshell |url=https://books.google.com/books?id=bG_Aqb6iOUYC&q=%22operator+overloading%22 |year=2003 |publisher=O'Reilly Media, Inc. |isbn=978-0-596-00526-9}}</ref>
*[[C++]]<ref>{{cite web |url=https://en.cppreference.com/w/cpp/language/operators |title=C++ Operator Overloading}}</ref>
*[[C++]]<ref>{{cite web |url=https://en.cppreference.com/w/cpp/language/operators |title=C++ Operator Overloading}}</ref>
*[[Ceylon (programming language)|Ceylon]]<ref>{{Cite web|title=Eclipse Ceylon: Operator Polymorphism|url=https://ceylon-lang.org/documentation/1.3/reference/operator/operator-polymorphism/|access-date=2021-04-07|website=ceylon-lang.org}}</ref>
*[[D (programming language)|D]]<ref>{{Cite web|title=Operator Overloading - D Programming Language|url=https://dlang.org/spec/operatoroverloading.html|access-date=2020-10-10|website=dlang.org}}</ref>
*[[D (programming language)|D]]<ref>{{Cite web|title=Operator Overloading - D Programming Language|url=https://dlang.org/spec/operatoroverloading.html|access-date=2020-10-10|website=dlang.org}}</ref>
*[[Dart (programming language)|Dart]]<ref>{{Cite web|title=A tour of the Dart language|url=https://dart.dev/guides/language/language-tour|access-date=2020-09-30|website=dart.dev}}</ref>
*[[Dart (programming language)|Dart]]<ref>{{Cite web|title=A tour of the Dart language|url=https://dart.dev/guides/language/language-tour|access-date=2020-09-30|website=dart.dev}}</ref>
*[[FreeBASIC]]<ref>{{Cite web|title=Operator Overloading|url=http://bourabai.kz/einf/freebasic/ProPgOperatorOverloading.html|access-date=2021-04-07|website=bourabai.kz}}</ref>
*[[Groovy (programming language)|Groovy]]<ref>{{Cite web|title=The Apache Groovy programming language - Operators|url=https://groovy-lang.org/operators.html#Operator-Overloading|access-date=2020-09-30|website=groovy-lang.org}}</ref>
*[[Groovy (programming language)|Groovy]]<ref>{{Cite web|title=The Apache Groovy programming language - Operators|url=https://groovy-lang.org/operators.html#Operator-Overloading|access-date=2020-09-30|website=groovy-lang.org}}</ref>
*[[Kotlin (programming language)|Kotlin]]<ref>{{cite web |title=Operator overloading |url=https://kotlinlang.org/docs/reference/operator-overloading.html |website=Kotlin |access-date=24 June 2018}}</ref>
*[[Kotlin (programming language)|Kotlin]]<ref>{{cite web |title=Operator overloading |url=https://kotlinlang.org/docs/reference/operator-overloading.html |website=Kotlin |access-date=24 June 2018}}</ref>
*[[Lua (programming language)|Lua]]<ref>{{cite web |url=http://lua-users.org/wiki/MetamethodsTutorial |title=Metamethods Tutorial |website=Lua-users Wiki}}</ref>
*[[Lua (programming language)|Lua]]<ref>{{cite web |url=http://lua-users.org/wiki/MetamethodsTutorial |title=Metamethods Tutorial |website=Lua-users Wiki}}</ref>
*[[MATLAB]]<ref>{{cite web |title=Implementing Operators for Your Class |url=http://www.mathworks.com/help/matlab/matlab_oop/implementing-operators-for-your-class.html |access-date=1 October 2013}}</ref>
*[[MATLAB]]<ref>{{cite web |title=Implementing Operators for Your Class |url=http://www.mathworks.com/help/matlab/matlab_oop/implementing-operators-for-your-class.html |access-date=1 October 2013 |archive-date=14 June 2024 |archive-url=https://web.archive.org/web/20240614070735/https://www.mathworks.com/help/matlab/matlab_oop/implementing-operators-for-your-class.html |url-status=dead }}</ref>
*[[Object Pascal]] ([[Free Pascal]],<ref>{{cite web |title=Operator Overloading |website=Free Pascal Manual |url=http://www.freepascal.org/docs-html/ref/refch15.html |access-date=1 December 2014}}</ref> [[Delphi (programming language)|Delphi]] (since 2005)<ref>{{cite web |title=Operator Overloading |website=Delphi Manual |url=http://docwiki.embarcadero.com/RADStudio/XE4/en/Operator_Overloading_%28Delphi%29 |access-date=1 December 2014}}</ref>)
*[[Object Pascal]] ([[Free Pascal]],<ref>{{cite web |title=Operator Overloading |website=Free Pascal Manual |url=http://www.freepascal.org/docs-html/ref/refch15.html |access-date=1 December 2014}}</ref> [[Delphi (programming language)|Delphi]] (since 2005)<ref>{{cite web |title=Operator Overloading |website=Delphi Manual |url=http://docwiki.embarcadero.com/RADStudio/XE4/en/Operator_Overloading_%28Delphi%29 |access-date=1 December 2014}}</ref>)
*[[PHP]] (using magic methods,<ref>{{cite web |title=PHP magic methods overriding class properties |url=http://webwidetutor.com/php/php-oop-Magic-Methods-tutorial-?id=30 |access-date=7 April 2015 |archive-url=https://web.archive.org/web/20160304050243/http://webwidetutor.com/php/php-oop-Magic-Methods-tutorial-?id=30 |archive-date=4 March 2016}}</ref> ArrayAccess interface, or Operator extension)
*[[PHP]] <ref>{{cite web |title=PHP magic methods overriding class properties |url=http://webwidetutor.com/php/php-oop-Magic-Methods-tutorial-?id=30 |access-date=7 April 2015 |archive-url=https://web.archive.org/web/20160304050243/http://webwidetutor.com/php/php-oop-Magic-Methods-tutorial-?id=30 |archive-date=4 March 2016}}</ref>
*[[Perl]]<ref name="Orwant2002">{{cite book |last=Orwant |first=Jon |title=Computer Science & Perl Programming: Best of The Perl Journal |url=https://books.google.com/books?id=8TkEOyBHoOoC&q=%22operator+overloading%22&pg=PA347 |date=4 November 2002 |publisher=O'Reilly Media, Inc. |isbn=978-0-596-00310-4 |pages=347–}}</ref>
*[[Perl]]<ref name="Orwant2002">{{cite book |last=Orwant |first=Jon |title=Computer Science & Perl Programming: Best of The Perl Journal |url=https://books.google.com/books?id=8TkEOyBHoOoC&q=%22operator+overloading%22&pg=PA347 |date=4 November 2002 |publisher=O'Reilly Media, Inc. |isbn=978-0-596-00310-4 |pages=347–}}</ref>
*[[Python (programming language)|Python]]<ref>{{cite web |url=https://docs.python.org/3/reference/datamodel.html |website=The Python Language Reference |title=3. Data Model}}</ref>
*[[Python (programming language)|Python]]<ref>{{cite web |url=https://docs.python.org/3/reference/datamodel.html |website=The Python Language Reference |title=3. Data Model}}</ref>
Line 155: Line 173:
==Timeline of operator overloading==
==Timeline of operator overloading==
===1960s===
===1960s===
The [[ALGOL 68]] specification allowed operator overloading.<ref>{{cite web |title=Report on the Algorithmic Language ALGOL 68, Section 10.2.2. |url=https://www.softwarepreservation.org/projects/ALGOL/report/Algol68_revised_report-AB-600dpi.pdf =Barry J. Mailloux |last3=Peck |first3=John E. L. |author-link3=John E. L. Peck |last4=Koster |first4= Cornelis H. A. |author-link4=Cornelis H.A. Koster |access-date=1 April 2007 |date=August 1968  |display-authors=etal}}</ref>
The [[ALGOL 68]] specification allowed operator overloading.<ref>{{cite web |title=Report on the Algorithmic Language ALGOL 68, Section 10.2.2. |url=https://www.softwarepreservation.org/projects/ALGOL/report/Algol68_revised_report-AB-600dpi.pdf |last1=van Wijngaarden |first1=A. |last2=Mailloux |first2=Barry J. |last3=Peck |first3=John E. L. |author-link3=John E. L. Peck |last4=Koster |first4= Cornelis H. A. |author-link4=Cornelis H.A. Koster |access-date=1 April 2007 |date=August 1968  |display-authors=etal}}</ref>


Extract from the ALGOL 68 language specification (page 177) where the overloaded operators ¬, =, ≠, and '''abs''' are defined:
Extract from the ALGOL 68 language specification (page 177) where the overloaded operators ¬, =, ≠, and '''abs''' are defined:
Line 180: Line 198:


===1990s===
===1990s===
[[Java (programming language)|Java]] language designers at [[Sun Microsystems]] chose to omit overloading.<ref>{{cite web |url=http://www.cafeaulait.org/javafaq.html#xtocid1902938 |website=The comp.lang.java FAQ List |title=FAQ Question 6.9: Why isn't there operator overloading?}}</ref><ref>{{cite web |url=http://java.sun.com/docs/white/langenv/Simple.doc2.html |title=java.sun.com |url-status=dead |access-date=26 March 2009 |archive-date=7 March 2009 |archive-url=https://web.archive.org/web/20090307035128/http://java.sun.com/docs/white/langenv/Simple.doc2.html }}</ref><ref>{{cite book |last=Holzner |first=Steven |title=C++: Black Book |year=2001 |publisher=Coriolis Group |location=Scottsdale, Arizona |isbn=1-57610-777-9 |page=387 |quote=One of the nicest features of C++ OOP is that you can overload operators to handle objects of your classes (you can't do this in some other OOP-centric languages, like Java).}}</ref>
[[Java (programming language)|Java]] language designers at [[Sun Microsystems]] chose to omit overloading.<ref>{{cite web |url=http://www.cafeaulait.org/javafaq.html#xtocid1902938 |website=The comp.lang.java FAQ List |title=FAQ Question 6.9: Why isn't there operator overloading?}}</ref><ref>{{cite web |url=http://java.sun.com/docs/white/langenv/Simple.doc2.html |title=java.sun.com |url-status=dead |access-date=26 March 2009 |archive-date=7 March 2009 |archive-url=https://web.archive.org/web/20090307035128/http://java.sun.com/docs/white/langenv/Simple.doc2.html }}</ref><ref>{{cite book |last=Holzner |first=Steven |title=C++: Black Book |year=2001 |publisher=Coriolis Group |location=Scottsdale, Arizona |isbn=1-57610-777-9 |page=387 |quote=One of the nicest features of C++ OOP is that you can overload operators to handle objects of your classes (you can't do this in some other OOP-centric languages, like Java).}}</ref> When asked about operator overloading, Brian Goetz of [[Oracle Corporation|Oracle]] responded "[[Value type]]s first, then we can talk about it.", suggesting that it could potentially be added after [[Project Valhalla (Java language)|Project Valhalla]].<ref>{{Cite tweet |user=BrianGoetz|number=819272509535219712|title=Value types first, then we can talk about it.}}</ref>


[[Python (programming language)|Python]] allows operator overloading through the implementation of methods with special names.<ref>{{cite web |url=https://docs.python.org/3/reference/datamodel.html#specialnames |website=The Python Language Reference |title=3. Data Model, Special method names}}</ref> For example, the addition (+) operator can be overloaded by implementing the method {{code|obj.__add__(self, other)}}.
[[Python (programming language)|Python]] allows operator overloading through the implementation of methods with special names.<ref>{{cite web |url=https://docs.python.org/3/reference/datamodel.html#specialnames |website=The Python Language Reference |title=3. Data Model, Special method names}}</ref> For example, the addition (+) operator can be overloaded by implementing the method {{code|obj.__add__(self, other)}}.
Line 189: Line 207:


===2000s===
===2000s===
Microsoft added operator overloading to [[C Sharp (programming language)|C#]] in 2001 and to [[Visual Basic .NET]] in 2003.
Microsoft added operator overloading to [[C Sharp (programming language)|C#]] in 2001 and to [[Visual Basic .NET]] in 2003. C# operator overloading is very similar in syntax to C++ operator overloading:<ref>{{Cite web|title=Operator overloading - predefined unary, arithmetic, equality, and comparison operators|url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading|website=learn.microsoft.com|publisher=Microsoft Learn|date=13 June 2025}}</ref>
<syntaxhighlight lang="csharp">
public class Fraction
{
    private int numerator;
    private int denominator;
 
    // ...
 
    public static Fraction operator +(Fraction lhs, Fraction rhs)
        => new Fraction(lhs.numerator * rhs.denominator + rhs.numerator * lhs.denominator, lhs.denominator * rhs.denominator);
}
</syntaxhighlight>


[[Scala (programming language)|Scala]] treats all operators as methods and thus allows operator overloading by proxy.
[[Scala (programming language)|Scala]] treats all operators as methods and thus allows operator overloading by proxy.


In [[Raku (programming language)|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]] source for incrementing a Date object with "+" is:
===2010s===


<syntaxhighlight lang="perl6">
In [[Raku (programming language)|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]] source for incrementing a Date object with "<code>+</code>" is:
 
<syntaxhighlight lang="raku">
multi infix:<+>(Date:D $d, Int:D $x) {
multi infix:<+>(Date:D $d, Int:D $x) {
     Date.new-from-daycount($d.daycount + $x)
     Date.new-from-daycount($d.daycount + $x)
Line 201: Line 233:
</syntaxhighlight>
</syntaxhighlight>


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.
Since "multi" was used, the function gets added to the list of [[multidispatch]] candidates, and "<code>+</code>" is only overloaded for the case where the type constraints in the function signature are met.
While the capacity for overloading includes '''+''', '''*''', '''>=''', the [[Imaginary unit|postfix and term '''i''']], and so on, it also allows for overloading various brace operators: "'''['''x, y''']'''", "x'''['''y''']'''", "x'''{''y''}'''", and "x'''('''y''')'''".
While the capacity for overloading includes <code>+</code>, <code>*</code>, <code>>=</code>, the [[Imaginary unit|postfix and term <code>i</code>]], and so on, it also allows for overloading various brace operators: <code>[x, y]</code>, <code>x[y]</code>, <code>x{y}</code>, and <code>x(y)</code>.
 
[[Kotlin (programming language)|Kotlin]] has supported operator overloading since its creation by overwriting specially named functions (like <code>plus()</code>, <code>inc()</code>, <code>rangeTo()</code>, etc.)<ref>{{Cite web|title=Operator overloading Kotlin|url=https://kotlinlang.org/docs/operator-overloading.html|website=kotlinlang.org|publisher=JetBrains s.r.o.|access-date=15 October 2025}}</ref>
<syntaxhighlight lang="Kotlin">
data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point): Point {
        return Point(this.x + other.x, this.y + other.y)
    }
}
</syntaxhighlight>
 
Because both Kotlin and Java compile to [[Java class file|{{mono|.class}}]], when converted back to [[Java (programming language)|Java]] this will just be represented as:
<syntaxhighlight lang="Java">
public class Point {
    // fields and constructor...
 
    public Point plus(Point other) {
        return new Point(this.x + other.x, this.y + other.y);
    }
}
</syntaxhighlight>
 
Operator overloading in [[Rust (programming language)|Rust]] is accomplished by implementing the [[Trait (computer programming)|trait]]s in <code>std::ops</code>.<ref>{{Cite web|title=Operator Overloading - Rust By Example|url=https://doc.rust-lang.org/rust-by-example/trait/ops.html|website=doc.rust-lang.org|publisher=Rust Programming Language|access-date=15 October 2025}}</ref>
<syntaxhighlight lang="Rust">
use std::ops::Add;
 
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32
}
 
impl Point {
    pub fn new(x: i32, y: i32) -> Self {
        Point {x, y}
    }
}


[[Kotlin (programming language)|Kotlin]] has supported operator overloading since its creation.
impl Add for Point {
    type Output = Point;
 
    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.y,
            y: self.y + other.y
        }
    }
}
 
fn main() {
    let p1: Point = Point::new(1, 2);
    let p2: Point = Point::new(3, 4);
    let sum: Point = p1 + p2;
    println!("Sum of p1 and p2: {:?}", sum);
}
</syntaxhighlight>


==See also==
==See also==

Revision as of 01:53, 16 November 2025

Template:Short description Template:Use American English Template:Use dmy dates Template:Polymorphism In computer programming, 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 programmer, or both.

Rationale Script error: No such module "anchor".

Operator overloading is syntactic sugar, and is used because it allows programming using notation nearer to the target domain[1] 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 a, b and c of some user-defined type, such as matrices:

a + b * c

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:

Add(a, Multiply(b, c))

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 Time in C++:

Time operator+(const Time& lhs, const Time& rhs) {
    Time temp = lhs;
    temp.seconds += rhs.seconds;
    temp.minutes += temp.seconds / 60;
    temp.seconds %= 60;
    temp.minutes += rhs.minutes;
    temp.hours += temp.minutes / 60;
    temp.minutes %= 60;
    temp.hours += rhs.hours;
    return temp;
}

Addition is a binary operation, which means it has two 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:

// The "const" right before the opening curly brace means that `this` is not modified.
Time Time::operator+(const Time& rhs) const {
    Time temp = *this;  // `this` should not be modified, so make a copy.
    temp.seconds += rhs.seconds;
    temp.minutes += temp.seconds / 60;
    temp.seconds %= 60;
    temp.minutes += rhs.minutes;
    temp.hours += temp.minutes / 60;
    temp.minutes %= 60;
    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;
}

The less-than (<) operator is often overloaded to sort a structure or class:

class IntegerPair {
private:
    int x;
    int y;
public:
    explicit IntegerPair(int x = 0, int y = 0):
        x{x}, y{y} {}

    bool operator<(const IntegerPair& p) const {
        if (x == p.x) {
            return y < p.y;
        }
        return x < p.x;
    }
};

Like with the previous examples, in the last example operator overloading is done within the class. In C++, after overloading the less-than operator (operator<), standard sorting functions can be used to sort some classes.

Starting in C++20 with the introduction of the three-way comparison operator (operator<=>), all the order operators can be defined by just defining that operator. The three-way comparison operator exists in many languages, including C++, Python, Rust, Swift, and PHP. Other languages, such as Java and C# instead use a method Comparable.compareTo().

import std;

using std::strong_ordering;

class IntegerPair {
private:
    int x;
    int y;
public:
    explicit IntegerPair(int x = 0, int y = 0):
        x{x}, y{y} {}

    // can be auto-generated with = default;
    strong_ordering operator<(const IntegerPair& p) const {
        if (strong_ordering cmp = x <=> p.x; cmp != strong_ordering::equal) {
            return cmp;
        }
        return y <=> p.y;
    }
};

Criticisms

Operator overloading has often been criticized[2] 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 a left by b bits if a and b are of an integer type, but if a is an output stream then the above code will attempt to write a b 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 decided not to use this feature,[3] 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 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. "bird" + "song" yields "birdsong", while "song" + "bird" yields "songbird"). A typical counterScript error: No such module "Unsubst". 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, 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.

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.

Operators Not overloadable Overloadable
New definable[4]
Limited set

Timeline of operator overloading

1960s

The ALGOL 68 specification allowed operator overloading.[36]

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.[37]

1990s

Java language designers at Sun Microsystems chose to omit overloading.[38][39][40] When asked about operator overloading, Brian Goetz of Oracle responded "Value types first, then we can talk about it.", suggesting that it could potentially be added after Project Valhalla.[41]

Python allows operator overloading through the implementation of methods with special names.[42] For example, the addition (+) operator can be overloaded by implementing the method obj.__add__(self, other).

Ruby 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. C# operator overloading is very similar in syntax to C++ operator overloading:[43]

public class Fraction
{
    private int numerator;
    private int denominator;

    // ...

    public static Fraction operator +(Fraction lhs, Fraction rhs)
        => new Fraction(lhs.numerator * rhs.denominator + rhs.numerator * lhs.denominator, lhs.denominator * rhs.denominator);
}

Scala treats all operators as methods and thus allows operator overloading by proxy.

2010s

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 source for incrementing a Date object with "+" is:

multi infix:<+>(Date:D $d, Int:D $x) {
    Date.new-from-daycount($d.daycount + $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{y}, and x(y).

Kotlin has supported operator overloading since its creation by overwriting specially named functions (like plus(), inc(), rangeTo(), etc.)[44]

data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point): Point {
        return Point(this.x + other.x, this.y + other.y)
    }
}

Because both Kotlin and Java compile to [[Java class file|Template:Mono]], when converted back to Java this will just be represented as:

public class Point {
    // fields and constructor...

    public Point plus(Point other) {
        return new Point(this.x + other.x, this.y + other.y);
    }
}

Operator overloading in Rust is accomplished by implementing the traits in std::ops.[45]

use std::ops::Add;

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32
}

impl Point {
    pub fn new(x: i32, y: i32) -> Self {
        Point {x, y}
    }
}

impl Add for Point {
    type Output = Point;

    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.y,
            y: self.y + other.y
        }
    }
}

fn main() {
    let p1: Point = Point::new(1, 2);
    let p2: Point = Point::new(3, 4);
    let sum: Point = p1 + p2;
    println!("Sum of p1 and p2: {:?}", sum);
}

See also

References

<templatestyles src="Reflist/styles.css" />

  1. Script error: No such module "citation/CS1".
  2. Script error: No such module "citation/CS1".
  3. Script error: No such module "citation/CS1".
  4. Completely new operators can be added.
  5. Script error: No such module "citation/CS1".
  6. Script error: No such module "citation/CS1".
  7. Script error: No such module "citation/CS1".
  8. Introduced in Fortran 90.
  9. Script error: No such module "citation/CS1".
  10. Type classes instead of overloading.
  11. Script error: No such module "citation/CS1".
  12. Script error: No such module "citation/CS1".
  13. Script error: No such module "citation/CS1".
  14. Script error: No such module "citation/CS1".
  15. Script error: No such module "citation/CS1".
  16. Script error: No such module "citation/CS1".
  17. Script error: No such module "citation/CS1".
  18. Script error: No such module "citation/CS1".
  19. Script error: No such module "citation/CS1".
  20. Script error: No such module "citation/CS1".
  21. Script error: No such module "citation/CS1".
  22. Script error: No such module "citation/CS1".
  23. Script error: No such module "citation/CS1".
  24. Script error: No such module "citation/CS1".
  25. Script error: No such module "citation/CS1".
  26. Script error: No such module "citation/CS1".
  27. Script error: No such module "citation/CS1".
  28. Script error: No such module "citation/CS1".
  29. Script error: No such module "citation/CS1".
  30. Script error: No such module "citation/CS1".
  31. Script error: No such module "citation/CS1".
  32. Script error: No such module "citation/CS1".
  33. Script error: No such module "citation/CS1".
  34. Script error: No such module "citation/CS1".
  35. Script error: No such module "citation/CS1".
  36. Script error: No such module "citation/CS1".
  37. Script error: No such module "citation/CS1".
  38. Script error: No such module "citation/CS1".
  39. Script error: No such module "citation/CS1".
  40. Script error: No such module "citation/CS1".
  41. Template:Cite tweet
  42. Script error: No such module "citation/CS1".
  43. Script error: No such module "citation/CS1".
  44. Script error: No such module "citation/CS1".
  45. Script error: No such module "citation/CS1".

Script error: No such module "Check for unknown parameters".

Template:Authority control