Programming Search⌘K

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)
Output
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

LanguageVerdictNote
PythonNative
C++Native
JavaAbsent
CAbsentC has no user operators; a program writes functions such as vec2_add.
C#Native
JavaScriptAbsent
TypeScriptAbsentAs JavaScript; a class cannot define operators; no example file because it would repeat the JavaScript answer.
GoAbsent
RustStandard library
KotlinNativeMember 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.
SQLDoes not applyStandard SQL has no user operators; PostgreSQL adds CREATE OPERATOR as an extension.
BashDoes not applyBash has no user types.
PowerShellIdiomPowerShell uses the operators that a .NET type defines, such as the static method op_Addition for +.
HTMLDoes not applyHTML has no operators.
CSSDoes not applyCalc() and the other CSS math functions have a fixed set of operators.
Regular expressionsDoes not applyRegular 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 operator keyword, and some come in pairs: "== and !=, < and >, <= and >=".3 && and || cannot be overloaded; a type overloads true, 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 == b always calls equals, and a < b calls compareTo.
  • 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 as BigInteger use methods: a.add(b).
  • JavaScript has no user operators, but it converts an object to a primitive for + and <. A class can define Symbol.toPrimitive; otherwise the language calls "the valueOf() and toString() methods in different orders".8
PythonGitHub
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)))
Output
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 NotImplemented for an operand that it does not know, so Python can try the other operand and then raise TypeError.
  • A class that defines __eq__ must also define __hash__ to stay usable in sets and as a dictionary key. sorted uses __lt__, and sum uses __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';
}
Output
Money(400)
true true true
Money(150)
  • Verdict: native. Operators are functions with names such as operator+= and operator==. 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 defaulted operator== gives == and !=. std::sort uses <.
  • operator<< for std::ostream lets std::cout print the object.
JavaGitHub
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));
    }
}
Output
Money[cents=400]
true
false
total: Money[cents=400]
1180591620717411303425
  • Verdict: absent. Java has no user operators, so a type has methods such as plus and equals. The standard BigInteger and BigDecimal work the same way, with add and multiply.
  • == on two objects compares references, so two equal records are not ==. Use equals, which the record generates.
  • + with a String operand joins strings and calls toString on 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);
}
Output
Money { Cents = 400 }
True
True
Money { Cents = 400 }
Money { Cents = 250 }
  • Verdict: native. An operator is a public static method declared with the operator keyword. 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 += m works too. Max uses IComparable<Money>, not the < operator.
JavaScriptGitHub
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));
Output
Money(400)
true
Money(150)Money(250)
false
  • Verdict: absent. A class cannot define what + or === does, so it has methods such as add and equals.
  • a + b converts both objects to primitives. Here toString gives 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}])
}
Output
{400}
true true
true
  • Verdict: absent. Go has no user operators, so Money has the methods Add and Less.
  • == 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 as func(x, y Money) int.
RustGitHub
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);
}
Output
Money(400)
true true
Money(450)
Money(400)
  • Verdict: stdlib. Each operator has a trait in std::ops: impl Add gives +, and impl Mul<i64> gives Money * i64. The associated type Output is the type of the result.
  • == and < come from PartialEq and PartialOrd, here derived from the field.
  • i64 * Money does not compile; it needs a separate impl Mul<Money> for i64. impl Sum lets Iterator::sum add the values.
  • 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] and f(x) are operators in some languages: Python's __getitem__ and __call__, C++'s operator[] and operator(), Rust's Index, and C#'s indexers.
  • Conversions. C++ conversion operators and C#'s implicit and explicit operators 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+ accepts v + 2 but not 2 + v, and in Python __add__ alone does not handle 2 + v. Use a non-member function in C++, and a reflected method such as __radd__ in Python.
  • Primitive conversions in JavaScript. A class with valueOf makes + and < work, but the result is a number, not an object of the class, and a template literal calls toString in place of valueOf:
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}`);
Output
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

  1. Operator overloading, cppreference.com, Restrictions; Binary arithmetic operators
  2. Data model, The Python Language Reference, 3.3.8 Emulating numeric types
  3. Operator overloading, C# reference, Overloadable operators; Non overloadable operators
  4. std::ops, Rust standard library, Description
  5. Operator overloading, Kotlin documentation, Introduction; Equality and inequality operators
  6. Frequently Asked Questions, The Go Programming Language, Why does Go not support overloading of methods and operators?
  7. Chapter 15: Expressions, The Java Language Specification, Java SE 21, 15.18 Additive Operators
  8. Symbol.toPrimitive, JavaScript reference, MDN, Description
  9. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/1VVHH0/text.yaml