C++
Summary - Operator overloading
Combine arithmetic, comparison and stream operators to write a Vector class.
Summary - Operator overloading
In this group you learned operator overloading. You define a function with the word operator and a symbol; your class then works like built-in types.
You saw arithmetic (+, -), comparison (==, <), stream (<<) and spaceship (<=>) operators. Now you will consolidate what you learned with two tasks: first the addition operator, then equality comparison.
Exercise Add operator+ to Vector2
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.
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(2, 3);
Vector2 b(4, 5);
Vector2 c = a + b;
std::cout << c.x << " " << c.y;
return 0;
}
Exercise Add operator== to Score
Add operator== to the Score class in the starting code: its body is return value == other.value;. In main compare a == b; print "Equal" if equal, "Different" otherwise.
Show example solution
#include <iostream>
class Score {
public:
int value;
Score(int v) : value(v) {}
bool operator==(const Score& other) const {
return value == other.value;
}
};
int main() {
Score a(7);
Score b(7);
if (a == b) {
std::cout << "Equal";
} else {
std::cout << "Different";
}
return 0;
}
End of section
You completed operator overloading. You can now define operator+, operator-, operator==, operator<< and operator<=>.
You made your classes work as naturally as built-in types. The next group is the intermediate final project; there you will combine OOP, templates, STL and file I/O. Operator overloading will also come in handy in that project.
Test yourself
-
What operator does operator+ define?
Vector2 operator+(const Vector2& other) const;
- Subtraction
- Addition
- Comparison
- Output
Show answer
Addition — operator+ is the addition operator.
-
Complete the operator function name
Vector2 ____(const Vector2& other) const { return Vector2(x + other.x, y + other.y); }
Show answer
Vector2 operator+(const Vector2& other) const { return Vector2(x + other.x, y + other.y); }
Next lesson: Project design