SyntaxStudy
Sign Up
C++ Operator Overloading
C++ Beginner 1 min read

Operator Overloading

C++ allows most built-in operators to be redefined for user-defined types through operator overloading. This capability makes custom types feel like first-class citizens of the language — a 'Vector2D' class can be added with '+', compared with '==', and streamed with '<<'. Overloaded operators are implemented as regular functions whose name begins with the keyword 'operator'. Operators can be overloaded as member functions or as free (non-member) functions. Binary operators where the left-hand operand must be convertible — such as the stream insertion operator '<<' — are commonly implemented as 'friend' free functions so that the standard library stream type appears on the left. Arithmetic and comparison operators are often free functions for symmetry. Not all operators should be overloaded for every type. The operator should behave intuitively, following the principle of least surprise. Overloading should preserve the conventional meaning: '+' should add, '<' should establish an ordering, and so on. Operators that cannot be overloaded include '.', '::', '?:', and 'sizeof'.
Example
#include <iostream>
#include <cmath>   // std::sqrt

struct Vector2D {
    double x, y;

    // Constructor
    Vector2D(double x = 0, double y = 0) : x(x), y(y) {}

    // Member: unary negation
    Vector2D operator-() const { return {-x, -y}; }

    // Member: compound assignment
    Vector2D& operator+=(const Vector2D& rhs) {
        x += rhs.x;  y += rhs.y;  return *this;
    }

    double length() const { return std::sqrt(x*x + y*y); }
};

// Free: binary addition (symmetrical)
Vector2D operator+(Vector2D lhs, const Vector2D& rhs) {
    lhs += rhs;   // reuse compound assignment
    return lhs;
}

// Free: equality
bool operator==(const Vector2D& a, const Vector2D& b) {
    return a.x == b.x && a.y == b.y;
}

// Free: stream insertion (friend not needed if using public members)
std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
    return os << "(" << v.x << ", " << v.y << ")";
}

int main() {
    Vector2D a{3.0, 0.0}, b{0.0, 4.0};
    Vector2D c = a + b;
    std::cout << "a + b = " << c << "\n";          // (3, 4)
    std::cout << "length = " << c.length() << "\n"; // 5
    std::cout << std::boolalpha << (a == b) << "\n"; // false
    return 0;
}