C++
Arithmetic operators
Learn to overload + and - operators.
Arithmetic operators
All arithmetic operators can be overloaded: +, -, *, /, %. Each is defined as an operator function.
Example: Vector2 operator-(const Vector2& other) const { return Vector2(x - other.x, y - other.y); }. This enables a - b and subtracts the components. The same structure works for operator* and operator/. Multiplication can also take a scalar: Vector2 operator*(int n) const;. Arithmetic operators are usually written as const members because they do not modify the object.
The subtraction operator
operator- gives the difference of two objects. Like addition it is written as a const member and returns a new object.
Example: Vector2 c = a - b; calls a.operator-(b) and gives c.x = a.x - b.x, c.y = a.y - b.y. Subtraction gives the vector from b (treated as origin) to a. In games and graphics this means relative position or velocity difference. Because the operator returns, chaining works too: a - b - c first computes a - b then subtracts c from the result.
Exercise Add operator- to the Vector2 class
Add operator- to the Vector2 class in the starting code: its body is return Vector2(x - other.x, y - other.y);. In main compute a - b and print the result's x and y with std::cout.
Show example solution
#include <iostream>
class Vector2 {
public:
int x;
int y;
Vector2(int x_, int y_) : x(x_), y(y_) {}
Vector2 operator-(const Vector2& other) const {
return Vector2(x - other.x, y - other.y);
}
};
int main() {
Vector2 a(5, 8);
Vector2 b(2, 3);
Vector2 c = a - b;
std::cout << c.x << " " << c.y;
return 0;
}
Test yourself
-
Match each operator to its operation
- operator+
- Addition
- operator-
- Subtraction
- operator*
- Multiplication
- operator/
- Division
-
Subtraction operator name
Vector2 ____(const Vector2& other) const { ... }
Show answer
Vector2 operator-(const Vector2& other) const { ... }
-
What does a - b return? (Vector2)
Vector2 a(5,8), b(2,3);
Vector2 c = a - b;
- Vector2(7, 11)
- Vector2(3, 5)
- Vector2(10, 24)
- Vector2(2, 3)
Show answer
Vector2(3, 5) — 5-2=3, 8-3=5 gives Vector2(3, 5).
Next lesson: Comparison operators