---
tag: P58DEX
kind: task
slug: overload-an-operator
name: Overload an operator
aliases: [overload plus, define operator plus, implement __add__, implement the Add trait, operator+ for a class, vector addition operator]
area: objects-and-classes/standard-object-methods
level: core
summary: Give a Vec2 type the operators + and == where the language allows user operators, and add and equals methods where it does not, then sum a list of vectors with them.
contract: contract.yaml
category: objects
languages: [python, javascript, typescript, java, c, cpp, csharp, go, rust]
see_also: [operator-overloading, operator, implement-equality-for-a-type, universal-object-methods, record-type]
sources:
  - url: https://docs.python.org/3/reference/datamodel.html
    title: Data model, The Python Language Reference
    locator: 3.3.8 Emulating numeric types; NotImplemented
  - url: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading
    title: Operator overloading, C# reference
    locator: Introduction; Overloadable operators
  - url: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record
    title: Records, C# reference
    locator: Value equality
  - url: https://doc.rust-lang.org/std/ops/index.html
    title: std::ops, Rust standard library
    locator: Description
  - url: https://en.cppreference.com/w/cpp/language/operators
    title: Operator overloading, cppreference.com
    locator: Restrictions; Binary arithmetic operators
  - url: https://go.dev/doc/faq
    title: Frequently Asked Questions, The Go Programming Language
    locator: Why does Go not support overloading of methods and operators?
  - url: https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html
    title: "Chapter 15: Expressions, The Java Language Specification, Java SE 21"
    locator: 15.18 Additive Operators
  - url: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive
    title: Symbol.toPrimitive, JavaScript reference, MDN
    locator: Description
  - url: https://doc.rust-lang.org/std/ops/trait.Add.html
    title: Add trait, Rust standard library
    locator: Description
---

## Task

Write a type `Vec2`, a vector in two dimensions with integer coordinates `x` and `y`. Give it addition, which adds the coordinates, and equality, which compares them. Where the language lets a type define operators, use `+` and `==`, so that `Vec2(1, 2) + Vec2(3, 4) == Vec2(4, 6)` is true. Where it does not, give the type methods with the same meaning, such as `add` and `equals`.

Then use the operator. The function `vector_sum(xs, ys)` makes the vector `Vec2(xs[i], ys[i])` for each index, adds all of them to the zero vector with `+`, and returns the coordinates of the sum as `[x, y]`. For example, `vector_sum([1, 3], [2, 4])` is `[4, 6]`. The lists have 0 to 10,000 items, each coordinate has an absolute value of 10^9 or less, and the tests also check `+` and `==` directly.

## Solutions

| Language | `+` | `==` | User operators |
|---|---|---|---|
| Python | `__add__` | `__eq__` and `__hash__` | yes, through special methods |
| JavaScript | an `add` method | an `equals` method | no |
| TypeScript | as JavaScript | as JavaScript | no |
| Java | a `plus` method | `equals`, generated by a record | no |
| C# | `static Vec2 operator +(Vec2 a, Vec2 b)` | generated by a `record struct` | yes |
| Go | an `Add` method | built in for structs with comparable fields | no |
| Rust | `impl Add for Vec2` | `#[derive(PartialEq, Eq)]` | yes, through traits |
| C | a function `vec2_add` | a function `vec2_equal` | no |
| C++ | `operator+=` as a member and `operator+` as a non-member | `operator==` with `= default` | yes |

- **Python** calls special methods for the operators: "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".[^1] `__add__` returns `NotImplemented` for an operand of another type, and Python then tries the other operand and at last raises `TypeError`. `vector_sum` passes the zero vector as the start value of `sum`, which then applies `+` to each item.
- **C#** declares operators with the `operator` keyword. A binary operator "has two input parameters", and "at least one parameter must have type T or T? where T is the type that contains the operator declaration".[^2] A `record struct` writes equality for the type, including "Overrides of operator == and operator !=".[^3]
- **Rust** maps each operator to a trait in `std::ops`: "the addition operator (+) can be overloaded through the Add trait".[^4] `Add` has an associated type `Output`, the type of the result. `#[derive(PartialEq, Eq)]` gives `==` and `!=`, and an `impl Sum` lets `Iterator::sum` add the vectors.
- **C++** defines `+=` as a member and `+` as a non-member function that uses it. cppreference gives the reason for the non-member: "Binary operators are typically implemented as non-members to maintain symmetry".[^5] A defaulted `operator==` compares the members. For `!=`, "overload resolution also considers the rewritten candidates operator==", so `a != b` works without a second operator.[^5]
- **Go** has no user operators. Its FAQ says: "Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it."[^6] The type has an `Add` method. `==` works without code, because the fields are comparable, and a `Vec2` can be a map key.
- **Java** has no user operators either. The specification allows `+` only for strings and numbers: "the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs".[^7] The record has a `plus` method, and it generates `equals` and `hashCode` from the two components.
- **JavaScript and TypeScript** have no user operators. The `+` operator converts an object to a primitive with `Symbol.toPrimitive`, "before falling back to using the object's valueOf() and toString() methods", so `a + b` on two vectors gives a string.[^8] The class has `add` and `equals`.
- **C** has functions in place of operators. `vec2_add` returns a new struct, and `vec2_equal` compares the fields.

### Alternatives

- **A mutating method.** `v.add_in_place(w)` changes `v` and makes no new object, which is faster in a hot loop. It is the role of `+=`; keep `+` free of side effects.
- **A free function.** In Go, C and Java, `Add(v, w)` as a function in place of a method treats both operands the same way, like the C++ non-member `operator+`.
- **The operator of a generic interface.** Rust's `Add<Rhs = Self>` lets the right operand have another type, such as a `Vec2 + i64`. `Rhs` "is Self by default, but this is not mandatory".[^9] Define such mixed operators only when the meaning is clear to a reader.

## Edge cases

The cases are in `cases/basic.jsonl` and `cases/edge.jsonl`.

- `empty`: no vectors give the zero vector, `[0, 0]`. The sum must start from the zero vector, not from the first item.
- `single`: one vector is its own sum.
- `negative`: negative coordinates add as numbers.
- `cancel`: two opposite vectors give the zero vector.
- `limit`: three coordinates of 10^9 give 3 × 10^9, which is more than a 32-bit `int` holds. The solutions use 64-bit integers; JavaScript numbers hold it exactly.

## Pitfalls

- **`sum` without a start value.** Python's `sum` starts from `0`, so the first step is `0 + Vec2(...)`, and `int` does not know `Vec2`:

```python run id=sum-needs-a-start
class Vec2:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        if not isinstance(other, Vec2):
            return NotImplemented
        return Vec2(self.x + other.x, self.y + other.y)


vectors = [Vec2(1, 2), Vec2(3, 4)]
try:
    sum(vectors)
except TypeError as e:
    print("TypeError:", e)
total = sum(vectors, Vec2(0, 0))
print(total.x, total.y)
```

```output for=sum-needs-a-start
TypeError: unsupported operand type(s) for +: 'int' and 'Vec2'
4 6
```

  Pass the zero vector as the start value, or define `__radd__` to accept `0`.
- **`==` that compares references.** In Java, `==` on two objects does not call `equals`: "If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality."[^7] This is true for records too, so use `equals`. In C#, a class that defines `operator ==` must also define `!=`; the operators "Must be overloaded in pairs".[^2]
- **An operator with a surprising meaning.** A reader expects `+` on vectors to add the coordinates. An operator that changes an operand, that is not symmetric, or that does work unrelated to its usual meaning makes code hard to read.
- **Raising an error in place of `NotImplemented`.** In Python, `__add__` that raises `TypeError` for another type stops Python from trying the other operand's `__radd__`. Numeric methods "should return this value if they do not implement the operation for the operands provided".[^1]
- **Overflow.** `+` on 32-bit coordinates overflows for large values. Choose a type that holds the largest sum.

## Related tasks

- [[implement-equality-for-a-type]] defines `==` and the hash for a value type in more detail.
- [[implement-ordering-for-a-type]] defines `<` and the other order operators.
- [[implement-a-string-form-for-a-type]] gives a value type a string form for test messages.

## References
