Arithmetic operators
- C++ course
- Intermediate
- Lesson 107/116
- 5 min
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.
Practice 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.
Starter code
#include <iostream>
class Vector2 {
public:
int x;
int y;
Vector2(int x_, int y_) : x(x_), y(y_) {}
// Add the subtraction operator
};
int main() {
Vector2 a(5, 8);
Vector2 b(2, 3);
// Compute a - b and print the result
return 0;
}Sample 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;
}Expected output
3 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each operator to its operation
| Term | Meaning |
|---|---|
operator+ |
Addition |
operator- |
Subtraction |
operator* |
Multiplication |
operator/ |
Division |
2 Subtraction operator name
Vector2 ____(const Vector2& other) const { ... }
Vector2 operator-(const Vector2& other) const { ... }
Explanation: operator- is the subtraction operator.
3 What does a - b return? (Vector2)
Vector2 a(5,8), b(2,3);
Vector2 c = a - b;- Vector2(7, 11)
- Vector2(3, 5) Correct answer
- Vector2(10, 24)
- Vector2(2, 3)
Explanation: 5-2=3, 8-3=5 gives Vector2(3, 5).