Lesson 2 of 5
Operator Overloading - Arithmetic, Comparison & Stream
Operator overloading lets user-defined types use C++ built-in operators (`+`, `-`, `==`, `<<`, etc.). The golden rule: **only overload operators when the meaning is obvious and consistent with the type's semantics**. Prefer **non-member friend functions** for symmetric operators (like `+`) - they allow implicit conversion on both sides. Member functions are best for operators that change the object (`+=`, `[]`, `()`).
Operator Overloading - All Key Operators with Best Practices
#include <iostream>
#include <string>
#include <compare> // C++20 spaceship operator
class Vec2 {
public:
double x, y;
Vec2(double x = 0.0, double y = 0.0) : x(x), y(y) {}
// ── Compound assignment - member (modifies *this) ─────────
Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; }
Vec2& operator-=(const Vec2& o) { x -= o.x; y -= o.y; return *this; }
Vec2& operator*=(double s) { x *= s; y *= s; return *this; }
Vec2& operator/=(double s) { x /= s; y /= s; return *this; }
// ── Unary operators - member ──────────────────────────────
Vec2 operator-() const { return {-x, -y}; } // negation
bool operator!() const { return x == 0.0 && y == 0.0; }
// ── Subscript - pair of const/non-const ──────────────────
double& operator[](int i) {
return (i == 0) ? x : y;
}
const double& operator[](int i) const {
return (i == 0) ? x : y;
}
// ── Conversion operator ───────────────────────────────────
explicit operator bool() const { return x != 0.0 || y != 0.0; }
// explicit prevents implicit bool conversion
double length() const { return std::sqrt(x*x + y*y); }
// ── Comparison (member for symmetric == / !=) would work but
// non-member friend below is more extensible ─────────────
friend bool operator==(const Vec2& a, const Vec2& b);
friend bool operator!=(const Vec2& a, const Vec2& b);
// ── Stream output - friend (accesses private internals) ───
friend std::ostream& operator<<(std::ostream& os, const Vec2& v);
friend std::istream& operator>>(std::istream& is, Vec2& v);
};
// ── Binary operators - non-member (symmetric conversion support) ──
// Implement +, -, * in terms of compound assignment (+=, -=, *=)
inline Vec2 operator+(Vec2 a, const Vec2& b) { return a += b; } // a is a copy
inline Vec2 operator-(Vec2 a, const Vec2& b) { return a -= b; }
inline Vec2 operator*(Vec2 v, double s) { return v *= s; }
inline Vec2 operator*(double s, Vec2 v) { return v *= s; } // commutative!
inline double dot(const Vec2& a, const Vec2& b) { return a.x*b.x + a.y*b.y; }
bool operator==(const Vec2& a, const Vec2& b) {
return a.x == b.x && a.y == b.y;
}
bool operator!=(const Vec2& a, const Vec2& b) { return !(a == b); }
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
return os << "(" << v.x << ", " << v.y << ")";
}
std::istream& operator>>(std::istream& is, Vec2& v) {
return is >> v.x >> v.y;
}
int main() {
Vec2 a{1.0, 2.0}, b{3.0, 4.0};
Vec2 c = a + b; // operator+(a, b)
Vec2 d = a - b;
Vec2 e = a * 2.0; // operator*(a, 2.0)
Vec2 f = 2.0 * a; // operator*(2.0, a) - commutative version!
std::cout << "a+b = " << c << "
"; // (4, 6)
std::cout << "a-b = " << d << "
"; // (-2, -2)
std::cout << "2*a = " << e << "
"; // (2, 4)
std::cout << "dot = " << dot(a, b) << "
"; // 11
a += b;
std::cout << "a+=b: " << a << "
"; // (4, 6)
std::cout << "a==b? " << (a == b) << "
"; // 0
std::cout << "a[0]=" << a[0] << "
"; // 4
Vec2 zero;
std::cout << "zero is " << (zero ? "nonzero" : "zero") << "
";
return 0;
}Common Mistakes
- Implementing `+` as a member instead of non-member - `Vec2 operator+(const Vec2& o)` as a member means `vec + 1.0` works but `1.0 + vec` doesn't (left operand can't be implicitly converted to Vec2 when it's on the left of a member call). Non-member friend solves this symmetrically.
- Forgetting to return `*this` from compound assignment - `+= -= *=` must return `Vec2&` (a reference to `*this`) to support chaining: `a += b += c`. Returning void makes chaining impossible.
- Overloading `&&`, `||`, or `,` - these operators have short-circuit evaluation semantics and sequencing semantics that are lost when overloaded. Never overload them. Also avoid overloading `&` (address-of) and `->*`.
Tip
Tip
Practice Operator Overloading Arithmetic Comparison Stream in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Arithmetic, relational, subscript, and stream insertion operator syntax
Practice Task
Note
Practice Task - (1) Write a working example of Operator Overloading Arithmetic Comparison Stream from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Operator Overloading Arithmetic Comparison Stream is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- Operator overloading lets user-defined types use C++ built-in operators (`+`, `-`, `==`, `<<`, etc.
- Implementing `+` as a member instead of non-member - `Vec2 operator+(const Vec2& o)` as a member means `vec + 1.0` works but `1.0 + vec` doesn't (left operand can't be implicitly converted to Vec2 when it's on the left of a member call). Non-member friend solves this symmetrically.
- Forgetting to return `*this` from compound assignment - `+= -= *=` must return `Vec2&` (a reference to `*this`) to support chaining: `a += b += c`. Returning void makes chaining impossible.
- Overloading `&&`, `||`, or `,` - these operators have short-circuit evaluation semantics and sequencing semantics that are lost when overloaded. Never overload them. Also avoid overloading `&` (address-of) and `->*`.
Finished this lesson?