Conceptcore
Operator overloading
Also called overloaded operators, operator functions, operator methods, special methods for operators, ad hoc operator polymorphism.
Operator overloading lets a type define what operators such as +, == and [] do for its values, so user types such as vectors and money can use the same syntax as numbers.
- Applies to
- core-languages
Idea
The built-in operators work on built-in types: + adds numbers and joins strings, and == compares numbers. Operator overloading lets a programmer give an operator a meaning for a new type. A vector type can define + as the sum of coordinates, a money type can define <, and a matrix type can define * and []. Code that uses such types then reads like arithmetic: a + b * c in place of a.add(b.multiply(c)).
An overloaded operator is a function with a special name or a special mark. The compiler or the interpreter turns a + b into a call of that function. The operator keeps its syntax: the precedence and the number of operands do not change. In C++, "It is not possible to change the precedence, grouping, or number of operands of operators."1
How it works
Each language maps an operator to a function. Python calls special methods: "to evaluate the expression x + y, where x is an instance of a class that has an add() method, type(x).add(x, y) is called".2 When the method cannot handle the other operand, it returns NotImplemented, and Python tries the reflected method of the right operand, such as __rmul__:
class Vec:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x + other.x, self.y + other.y)
def __mul__(self, k):
if not isinstance(k, int):
return NotImplemented
return Vec(self.x * k, self.y * k)
__rmul__ = __mul__
def __repr__(self):
return f"Vec({self.x}, {self.y})"
v = Vec(1, 2)
print(v + Vec(3, 4))
print(v * 3)
print(3 * v)
try:
v + 1
except TypeError as e:
print("TypeError:", e)
Vec(4, 6)
Vec(3, 6)
Vec(3, 6)
TypeError: unsupported operand type(s) for +: 'Vec' and 'int'
3 * v works because int.__mul__ returns NotImplemented for a Vec, and Python then calls v.__rmul__(3). v + 1 fails, because neither side knows the other.
The other languages that allow overloading use one of three forms:
| Form | Languages | a + b becomes |
|---|---|---|
| a special method name | Python, Kotlin | a.__add__(b), a.plus(b) |
| a function named with a keyword | C++, C# | operator+(a, b) or a.operator+(b) |
| a trait or an interface | Rust | Add::add(a, b) |
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Absent | |
| C | Absent | C has no user operators; a program writes functions such as vec2_add. |
| C# | Native | |
| JavaScript | Absent | |
| TypeScript | Absent | As JavaScript; a class cannot define operators; no example file because it would repeat the JavaScript answer. |
| Go | Absent | |
| Rust | Standard library | |
| Kotlin | Native | Member or extension functions marked operator, such as plus, minus, get and compareTo, give the operators; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | Standard SQL has no user operators; PostgreSQL adds CREATE OPERATOR as an extension. |
| Bash | Does not apply | Bash has no user types. |
| PowerShell | Idiom | PowerShell uses the operators that a .NET type defines, such as the static method op_Addition for +. |
| HTML | Does not apply | HTML has no operators. |
| CSS | Does not apply | Calc() and the other CSS math functions have a fixed set of operators. |
| Regular expressions | Does not apply | Regular expressions have no user types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | special methods such as __add__, __radd__, __eq__ and __getitem__ |
| JavaScript | absent | no user operators; valueOf and Symbol.toPrimitive convert objects to primitives |
| TypeScript | absent | as JavaScript |
| Java | absent | no user operators; + joins strings |
| Kotlin | native | member or extension functions marked operator, such as plus and get |
| C# | native | public static methods declared with operator |
| Go | absent | no user operators; == works on comparable structs |
| Rust | stdlib | traits of std::ops, such as Add, Mul, Index and Neg; PartialEq for == |
| C | absent | no user operators |
| C++ | native | functions named operator+, operator==, operator[] and more |
| Bash | n/a | no user types |
| PowerShell | idiom | .NET operators of a type, such as op_Addition, work in PowerShell expressions |
| SQL | n/a | no user operators in standard SQL; PostgreSQL has CREATE OPERATOR |
| Regex | n/a | no user types |
| HTML | n/a | no operators |
| CSS | n/a | calc() has fixed operators |
- C++ allows most operators. Exceptions are
::,.,.*and?:, and "New operators such as **, <>, or &| cannot be created."1 Binary operators are often free functions: "Binary operators are typically implemented as non-members to maintain symmetry".1 - C# declares operators with the
operatorkeyword, and some come in pairs: "== and !=, < and >, <= and >=".3&&and||cannot be overloaded; a type overloadstrue,false,&and|instead. - Rust ties each operator to a trait: "Implementing these traits allows you to overload certain operators."4 Only operators with a trait can change: "since the assignment operator (=) has no backing trait, there is no way of overloading its semantics".4
- Kotlin maps each operator to a function with a fixed name: "To overload an operator, mark the corresponding function with the operator modifier".5
a == balways callsequals, anda < bcallscompareTo. - Go leaves the feature out on purpose: "Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it."6
- Java gives
+a meaning only for strings and numbers; any other operand type is "a compile-time error".7 Types such asBigIntegeruse methods:a.add(b). - JavaScript has no user operators, but it converts an object to a primitive for
+and<. A class can defineSymbol.toPrimitive; otherwise the language calls "the valueOf() and toString() methods in different orders".8
class Money:
def __init__(self, cents):
self.cents = cents
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.cents + other.cents)
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents == other.cents
def __hash__(self):
return hash(self.cents)
def __lt__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents < other.cents
def __repr__(self):
return f"Money({self.cents})"
a, b = Money(150), Money(250)
print(a + b)
print(a + b == Money(400), a < b)
print(sorted([b, a]))
print(sum([a, b], Money(0)))
Money(400)
True True
[Money(150), Money(250)]
Money(400)
- Verdict: native. Each operator calls a special method:
+calls__add__,==calls__eq__and<calls__lt__. - A method returns
NotImplementedfor an operand that it does not know, so Python can try the other operand and then raiseTypeError. - A class that defines
__eq__must also define__hash__to stay usable in sets and as a dictionary key.sorteduses__lt__, andsumuses__add__from the start value.
#include <algorithm>
#include <compare>
#include <iostream>
#include <vector>
class Money {
public:
explicit Money(long long cents) : cents_(cents) {}
Money& operator+=(const Money& other) {
cents_ += other.cents_;
return *this;
}
// == and <=> from the member; C++20 derives !=, <, <=, > and >=.
friend bool operator==(const Money&, const Money&) = default;
friend auto operator<=>(const Money&, const Money&) = default;
friend std::ostream& operator<<(std::ostream& os, const Money& m) {
return os << "Money(" << m.cents_ << ")";
}
private:
long long cents_;
};
// A non-member + that uses +=.
Money operator+(Money a, const Money& b) {
a += b;
return a;
}
int main() {
Money a{150}, b{250};
std::cout << a + b << '\n';
std::cout << std::boolalpha << (a + b == Money{400}) << ' ' << (a < b)
<< ' ' << (a != b) << '\n';
std::vector<Money> v{b, a};
std::sort(v.begin(), v.end());
std::cout << v.front() << '\n';
}
Money(400)
true true true
Money(150)
- Verdict: native. Operators are functions with names such as
operator+=andoperator==. The member+=changes the object, and the non-member+copies its left operand and uses+=. - A defaulted
operator<=>compares the members, and the compiler rewrites<,>,<=and>=to use it; a defaultedoperator==gives==and!=.std::sortuses<. operator<<forstd::ostreamletsstd::coutprint the object.
import java.math.BigInteger;
public class Main {
record Money(long cents) {
Money plus(Money other) {
return new Money(cents + other.cents);
}
}
public static void main(String[] args) {
Money a = new Money(150);
Money b = new Money(250);
System.out.println(a.plus(b));
System.out.println(a.plus(b).equals(new Money(400)));
System.out.println(a.plus(b) == new Money(400));
System.out.println("total: " + a.plus(b));
BigInteger big = BigInteger.TWO.pow(70);
System.out.println(big.add(BigInteger.ONE));
}
}
Money[cents=400]
true
false
total: Money[cents=400]
1180591620717411303425
- Verdict: absent. Java has no user operators, so a type has methods such as
plusandequals. The standardBigIntegerandBigDecimalwork the same way, withaddandmultiply. ==on two objects compares references, so two equal records are not==. Useequals, which the record generates.+with aStringoperand joins strings and callstoStringon the other operand.
using System;
using System.Linq;
var a = new Money(150);
var b = new Money(250);
Console.WriteLine(a + b);
Console.WriteLine(a + b == new Money(400));
Console.WriteLine(a < b);
var total = new Money(0);
foreach (var m in new[] { a, b }) total += m;
Console.WriteLine(total);
Console.WriteLine(new[] { b, a }.Max());
readonly record struct Money(long Cents) : IComparable<Money>
{
public static Money operator +(Money x, Money y) => new(x.Cents + y.Cents);
// < and > must be defined as a pair.
public static bool operator <(Money x, Money y) => x.Cents < y.Cents;
public static bool operator >(Money x, Money y) => x.Cents > y.Cents;
public int CompareTo(Money other) => Cents.CompareTo(other.Cents);
}
Money { Cents = 400 }
True
True
Money { Cents = 400 }
Money { Cents = 250 }
- Verdict: native. An operator is a
public staticmethod declared with theoperatorkeyword. At least one parameter has the type that declares it. - The record struct generates
==and!=from the fields.<and>must be declared together. - With
+defined,total += mworks too.MaxusesIComparable<Money>, not the<operator.
class Money {
constructor(cents) {
this.cents = cents;
}
add(other) {
return new Money(this.cents + other.cents);
}
equals(other) {
return other instanceof Money && this.cents === other.cents;
}
toString() {
return `Money(${this.cents})`;
}
}
const a = new Money(150);
const b = new Money(250);
console.log(`${a.add(b)}`);
console.log(a.add(b).equals(new Money(400)));
console.log(a + b);
console.log(new Money(1) === new Money(1));
Money(400)
true
Money(150)Money(250)
false
- Verdict: absent. A class cannot define what
+or===does, so it has methods such asaddandequals. a + bconverts both objects to primitives. HeretoStringgives strings, so+joins them.===on two objects compares references, so two equal values are not===.
package main
import "fmt"
type Money struct {
Cents int64
}
func (m Money) Add(other Money) Money {
return Money{m.Cents + other.Cents}
}
func (m Money) Less(other Money) bool {
return m.Cents < other.Cents
}
func main() {
a, b := Money{150}, Money{250}
fmt.Println(a.Add(b))
fmt.Println(a.Add(b) == Money{400}, a.Less(b))
seen := map[Money]bool{a: true}
fmt.Println(seen[Money{150}])
}
{400}
true true
true
- Verdict: absent. Go has no user operators, so
Moneyhas the methodsAddandLess. ==is built in for a struct whose fields are comparable: it compares the fields. Such a struct can also be a map key.<does not work on structs; a sort takes a function such asfunc(x, y Money) int.
use std::iter::Sum;
use std::ops::{Add, Mul};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Money(i64);
impl Add for Money {
type Output = Money;
fn add(self, other: Money) -> Money {
Money(self.0 + other.0)
}
}
// Money * i64, with an operand of another type.
impl Mul<i64> for Money {
type Output = Money;
fn mul(self, k: i64) -> Money {
Money(self.0 * k)
}
}
impl Sum for Money {
fn sum<I: Iterator<Item = Money>>(iter: I) -> Money {
iter.fold(Money(0), |acc, m| acc + m)
}
}
fn main() {
let a = Money(150);
let b = Money(250);
println!("{:?}", a + b);
println!("{} {}", a + b == Money(400), a < b);
println!("{:?}", a * 3);
let total: Money = vec![a, b].into_iter().sum();
println!("{:?}", total);
}
Money(400)
true true
Money(450)
Money(400)
- Verdict: stdlib. Each operator has a trait in
std::ops:impl Addgives+, andimpl Mul<i64>givesMoney * i64. The associated typeOutputis the type of the result. ==and<come fromPartialEqandPartialOrd, here derived from the field.i64 * Moneydoes not compile; it needs a separateimpl Mul<Money> for i64.impl SumletsIterator::sumadd the values.
Variations and related ideas
- New operators. ALGOL 68, Haskell, Scala and Swift let a program define new operator symbols with their own precedence. C++, C#, Rust, Kotlin and Python allow only the existing symbols.9
- Equality and comparison.
==and<are operators, but their rules come from the equality and ordering contracts: equal objects need equal hash codes, and an order must be consistent. Records, data classes and Rust's#[derive(PartialEq, Ord)]generate them. - Indexing and calling.
a[i]andf(x)are operators in some languages: Python's__getitem__and__call__, C++'soperator[]andoperator(), Rust'sIndex, and C#'s indexers. - Conversions. C++ conversion operators and C#'s
implicitandexplicitoperators let a type change into another type. Implicit conversions can make an overloaded operator apply where the reader does not expect it. - Function overloading. Operator overloading is a special case of overloading by type: the compiler picks the operator function from the types of the operands. See operator for the built-in operators.
Pitfalls
- A surprising meaning. Wikipedia notes a common criticism: overloading lets a programmer change the usual meaning of an operator, which can surprise the next reader.9 C++'s
<<both shifts bits and writes to a stream. Use an operator only when its meaning for the type is the usual one, such as+for a sum. - Lost short-circuit evaluation. The built-in
&&and||skip the right operand when the left one decides the result. In C++, "The overloads of operators && and || lose short-circuit evaluation."1 Rust and C# do not let a type overload them directly.43 - Asymmetric operands. A C++ member
operator+acceptsv + 2but not2 + v, and in Python__add__alone does not handle2 + v. Use a non-member function in C++, and a reflected method such as__radd__in Python. - Primitive conversions in JavaScript. A class with
valueOfmakes+and<work, but the result is a number, not an object of the class, and a template literal callstoStringin place ofvalueOf:
class Money {
constructor(cents) {
this.cents = cents;
}
valueOf() {
return this.cents;
}
}
const a = new Money(150);
const b = new Money(250);
console.log(a + b);
console.log(a < b);
console.log(`${a}`);
400
true
[object Object]
==that is not an equivalence. An overloaded==must be reflexive, symmetric and transitive, and it must agree with the hash. An==that compares with a tolerance, or that accepts other types, breaks hash tables and sets.
Cost
An overloaded operator is a function call, so it costs the same as the method that it replaces. In C++, Rust and C# the compiler can inline small operator functions, so a + b on a small struct costs as much as the code for the fields. An operator that returns a new object on each step, such as + on large matrices or strings in a loop, allocates a temporary each time; compound operators such as += that change an operand in place avoid it.
History
ALGOL 68 allowed operator overloading, and programs could also define new operators and set their priority.9 Ada had overloading of the existing operators from Ada 83, but not new operators. C++ took the idea from ALGOL 68 with changes, and C# added it in 2001.9 The designers of Java left it out, and Go also chose not to have it.96 Python, Kotlin and Rust later tied operators to methods or traits with fixed names.
References
- Operator overloading, cppreference.com, Restrictions; Binary arithmetic operators
- Data model, The Python Language Reference, 3.3.8 Emulating numeric types
- Operator overloading, C# reference, Overloadable operators; Non overloadable operators
- std::ops, Rust standard library, Description
- Operator overloading, Kotlin documentation, Introduction; Equality and inequality operators
- Frequently Asked Questions, The Go Programming Language, Why does Go not support overloading of methods and operators?
- Chapter 15: Expressions, The Java Language Specification, Java SE 21, 15.18 Additive Operators
- Symbol.toPrimitive, JavaScript reference, MDN, Description
- Operator overloading, Wikipedia, Criticisms; ALGOL 68; Ada; C#; Java
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 1VVHH0 Edit this page History Report an error Markdown