Arithmetic and Comparison Operators
Overload +, -, *, /, ==, < and friends following best practices.
Why Overload Operators?
Operator overloading lets your types behave like built-in types — v1 + v2 reads better than v1.add(v2). Use it for value types like vectors, complex numbers, money.
Defining operator+
You can overload + as a member or a free function. Free functions are more symmetric.
struct Vec2 {
double x, y;
Vec2 operator+(const Vec2& other) const {
return {x + other.x, y + other.y};
}
};All lessons in this course
- Arithmetic and Comparison Operators
- Stream Insertion and Extraction Operators
- Subscript and Function Call Operators
- Three-Way Comparison Operator C++20