Courses/C++/Operator Overloading

    Lesson 24 • Advanced

    Operator Overloading

    Overload arithmetic, comparison, subscript, function call, and conversion operators correctly and safely.

    What You'll Learn

    • Arithmetic and comparison operators
    • Subscript [] and function call () operators
    • Stream insertion operator <<
    • Conversion operators (explicit/implicit)

    Arithmetic & Stream Operators

    Build a Vector2D class with full operator support

    Try it Yourself »
    C++
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    class Vector2D {
    public:
        double x, y;
        
        Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
        
        // Arithmetic operators (member functions)
        Vector2D operator+(const Vector2D& o) const { return {x + o.x, y + o.y}; }
        Vector2D operator-(const Vector2D& o) const { return {x - o.x, y - o.y}; }
        Vector2D operator*(double scalar) const { return {x * scalar, y * scalar}; }
        
        // Compound assignment
        Vector2D& 
    ...

    Subscript & Function Call Operators

    Create safe arrays with [] and functors with ()

    Try it Yourself »
    C++
    #include <iostream>
    #include <stdexcept>
    #include <vector>
    using namespace std;
    
    // Subscript operator [] for safe array access
    class SafeArray {
        vector<int> data;
    public:
        SafeArray(int size, int val = 0) : data(size, val) {}
        
        // Non-const version (read/write)
        int& operator[](int index) {
            if (index < 0 || index >= (int)data.size()) {
                throw out_of_range("Index " + to_string(index) + " out of range");
            }
            return data[index];
        }
        
        // C
    ...

    Conversion Operators & Fractions

    Build a Fraction class with arithmetic, comparison, and type conversions

    Try it Yourself »
    C++
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Fraction {
        int num, den;
        
        int gcd(int a, int b) const {
            a = abs(a); b = abs(b);
            while (b) { a %= b; swap(a, b); }
            return a;
        }
        
        void simplify() {
            int g = gcd(num, den);
            num /= g; den /= g;
            if (den < 0) { num = -num; den = -den; }
        }
        
    public:
        Fraction(int n = 0, int d = 1) : num(n), den(d) {
            if (d == 0) throw invalid_argument("Denominator cann
    ...

    Common Mistakes

    ⚠️ Implicit conversions: Non-explicit conversion operators can cause surprising implicit casts. Always use explicit unless you specifically want implicit conversion.

    ⚠️ Breaking symmetry: If a + b works, b + a should too. Use non-member functions for symmetric operators.

    ⚠️ Not returning *this: Compound assignment operators (+=, -=) must return a reference to *this for chaining.

    Pro Tips

    💡 Implement + using +=: Write operator+= first, then implement operator+ as a non-member using +=. Less code, fewer bugs.

    💡 Spaceship operator (C++20): operator<=> auto-generates all six comparison operators from one definition.

    💡 Don't overload &&, ||, or comma: These operators lose short-circuit evaluation when overloaded. It's almost never worth it.

    📋 Quick Reference

    OperatorMember or Non-member?
    =, [], (), ->Must be member
    +=, -=, *=Should be member
    +, -, *, ==Prefer non-member
    <<, >>Must be non-member (or friend)

    Lesson Complete!

    You can now overload operators idiomatically and safely. Next: Concurrency in C++ — threads, futures, promises, and async.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service