Operator functions
- C++ course
- Intermediate
- Lesson 106/116
- 5 min
Learn to define operator functions.
Operator functions
An operator function redefines operators like +, -, == for your own class. The function name is the word operator followed by the operator symbol.
Example: Vector2 operator+(const Vector2& other) const;. This lets you add two Vector2 objects with +. The call Vector2 c = a + b; actually calls a.operator+(b). The const keyword marks that the method does not modify the object. Operator overloading lets you use your classes as naturally as built-in types.
Defining as a member
An operator function can be defined as a member of the class. In that case the left side is the object itself and the right side is the parameter.
Example: Vector2 operator+(const Vector2& other) const { return Vector2(x + other.x, y + other.y); }. Here this->x and other.x are added and a new Vector2 is returned. The expression a + b calls operator+ on a and passes b as the parameter. The const method does not modify a; so after a + b the object a stays the same.
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 addition operator
};
int main() {
Vector2 a(1, 2);
Vector2 b(3, 4);
// 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(1, 2);
Vector2 b(3, 4);
Vector2 c = a + b;
std::cout << c.x << " " << c.y;
return 0;
}Expected output
4 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the operator function name
Vector2 ____(const Vector2& other) const;
Vector2 operator+(const Vector2& other) const;
Explanation: The operator+ function defines the + operator.
2 What does a + b call?
Vector2 a(1,2), b(3,4);
Vector2 c = a + b;- a.operator+(b) Correct answer
- operator+(a, b)
- b.operator+(a)
- a.plus(b)
Explanation: a + b calls operator+ on a and passes b as parameter.
3 Match each piece to its role
| Term | Meaning |
|---|---|
operator+ |
Addition |
operator |
Prefix |
const |
Does not modify |
return Vector2( |
Returning a new object |