ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C++ Tutorial• 6 min read

Operator Overloading: Custom Type Ergonomics

Overloading +, ==, and the << stream insertion operator

Operator overloading enables custom classes to use standard mathematical and comparison operators (+, -, ==, <<), making custom types feel like built-in language primitives.

Overloading Operators Cleanly

Syntax: ReturnType operator+(const ClassName &other) const;.

Overloading <<: Implemented as a non-member friend function to allow custom classes to be output directly via std::cout << myObj;.

Vector2D Class with Overloaded + and <<
#include <iostream>

class Vector2D {
public:
    double x, y;
    Vector2D(double x, double y) : x(x), y(y) {}

    // Overload + operator
    Vector2D operator+(const Vector2D &other) const {
        return Vector2D(x + other.x, y + other.y);
    }

    // Overload stream output operator <<
    friend std::ostream &operator<<(std::ostream &os, const Vector2D &v) {
        return os << "(" << v.x << ", " << v.y << ")";
    }
};

int main() {
    Vector2D v1(1.5, 2.0);
    Vector2D v2(3.0, 4.5);
    Vector2D sum = v1 + v2; // Clean natural syntax!
    std::cout << "Sum: " << sum << std::endl; // Output: (4.5, 6.5)
    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which operator is overloaded to allow sending custom objects directly to `std::cout`?