0Pricing
C++ Academy · Lesson

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

  1. Arithmetic and Comparison Operators
  2. Stream Insertion and Extraction Operators
  3. Subscript and Function Call Operators
  4. Three-Way Comparison Operator C++20
← Back to C++ Academy