SyntaxPilot
Courses/C++/Lesson 17

C++ · Lesson 17 of 40 · 12 min

Operator overloading

queued

These are the notes for C++ episode 17. Episode 16 ended with a question: can you add two of your own objects with a plus sign, or print one with cout? Here you'll see why a + b fails for your own class, fix it with operator overloading (operator+), keep objects valid in the constructor, print objects with a non-member operator<< that returns ostream&, compare them with operator==, and learn the rules: what you can and can't overload. The mini project is a shopping cart with a Money class. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.

The problem: a train trip in two legs

You're planning a train trip:

Leg Time
Delhi → Jaipur 4 h 45 min
Jaipur → Udaipur 6 h 30 min
Total 11 h 15 min

You add these in your head without thinking. In code, a journey time is our own class, Duration, with private hours and minutes (encapsulation, episode 14) and two getters. The natural thing to write is a + b:

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh), m(mm) {}
    int hours() const { return h; }
    int mins() const { return m; }
};

int main() {
    Duration a(4, 45), b(6, 30);
    Duration total = a + b;
    cout << total.hours() << "h " << total.mins() << "m" << endl;
    return 0;
}
error: no match for 'operator+' (operand types are 'Duration' and 'Duration')

Why? The + operator is built in only for built-in types (int, double, char, pointers). Duration is a type you made. C++ has no idea what adding two of them should mean: add the hours? join them? You have to tell it.

Attempt 2: a normal add() function

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh), m(mm) {}
    int hours() const { return h; }
    int mins() const { return m; }
};
Duration add(const Duration& x, const Duration& y) {
    return Duration(x.hours() + y.hours(), x.mins() + y.mins());
}

int main() {
    Duration a(4, 45), b(6, 30), c(2, 15);
    Duration total = add(add(a, b), c);
    cout << total.hours() << "h " << total.mins() << "m" << endl;
    return 0;
}

Output:

12h 90m

It works, but two problems:

  1. add(add(a, b), c) is hard to read. With ten legs it's a bracket nightmare. We want a + b + c, like maths.
  2. 12h 90m: technically correct, but no timetable says 90 minutes. We fix that below.

The fix: operator+

An operator function is an ordinary function with a special name: the word operator followed by the symbol. When you write a + b and a is a Duration, the compiler turns it into a call:

a + b        // what you write
a.operator+(b)   // what the compiler calls (member version)

That's operator overloading: giving an existing operator a meaning for your own type. Think of a calculator's + button: it only knows numbers. You write the rule for times once (add hours, add minutes), and from then on everyone just says "plus".

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh), m(mm) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
};

int main() {
    Duration a(4, 45), b(6, 30);
    Duration total = a + b;
    cout << total.hours() << "h " << total.mins() << "m" << endl;
    return 0;
}

Output:

10h 75m

Line by line:

  • Duration operator+(const Duration& o) const: returns a new Duration; takes the right-hand side o by const reference (no copy, can't be changed); the final const promises that a + b doesn't change a. That's what + means for numbers too: x + y doesn't change x.
  • It's a member function, so it can read o.h and o.m directly, even though they're private: privacy is per class, not per object.

Keeping objects valid: normalise in the constructor

10h 75m is a silly state. Where should the fix go? Not in operator+: any Duration could be built with 75 minutes (Duration(1, 75)). Fix it in the one place every Duration is born, the constructor:

Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
  • mm / 60 is integer division: 75 / 60 is 1 extra hour.
  • mm % 60 is the remainder (modulo): 75 % 60 is 15 minutes left.
#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
};

int main() {
    Duration a(4, 45), b(6, 30);
    Duration total = a + b;
    cout << total.hours() << "h " << total.mins() << "m" << endl;
    return 0;
}

Output:

11h 15m

The constructor guards the rule ("minutes are always 0-59"), so every other function, including operator+, can stay simple. This is called keeping a class invariant: a rule that is true for every object at all times.

Printing with cout: operator<<

We're still printing with total.hours() << "h " << total.mins() << "m" every time. We want cout << total:

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
};

int main() {
    Duration a(4, 45), b(6, 30);
    Duration total = a + b;
    cout << total << endl;
    return 0;
}
error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'Duration')

std::ostream is the type of cout (an output stream). This time the left operand is cout, not our Duration. That matters:

  • A member operator always has your object on the left: a + b → a.operator+(b).
  • cout << total would have to be cout.operator<<(total), a member of ostream. That class belongs to the standard library; we can't add members to it.
  • So we write operator<< as a non-member (a normal function outside the class) with two parameters: cout << total → operator<<(cout, total).

Why it must return ostream& (chaining)

cout << total << endl is really (cout << total) << endl. The first call must hand cout back, like a baton in a relay race, so the second << has a stream to work with. If it returns void, the chain breaks:

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
};
void operator<<(ostream& out, const Duration& d) {
    out << d.hours() << "h " << d.mins() << "m";
}

int main() {
    Duration a(4, 45), b(6, 30);
    Duration total = a + b;
    cout << total << endl;
    return 0;
}
error: invalid operands of types 'void' and '<unresolved overloaded function type>' to binary 'operator<<'

(void << endl means nothing; endl is a function template, which is why g++ calls it an "unresolved overloaded function type".)

The fix: return ostream& and end with return out;. It's a reference because streams can't be copied (there is only one cout).

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
};
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.hours() << "h " << d.mins() << "m";
    return out;
}

int main() {
    Duration a(4, 45), b(6, 30);
    Duration total = a + b;
    cout << total << endl;
    return 0;
}

Output:

11h 15m

Notice: this function isn't a member, so it can't see the private h and m; it uses the public getters. Episode 18 shows a neater answer: a friend function.

Because it takes ostream& (not specifically cout), the same function also works with cerr, file streams (episode 32) and string streams.

Comparing: operator==

Is the bus (11 h 15) as fast as the train (4 h 45 + 6 h 30)?

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
};
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.hours() << "h " << d.mins() << "m";
    return out;
}

int main() {
    Duration bus(11, 15), train(4, 45);
    train = train + Duration(6, 30);
    if (bus == train) cout << "Same time: " << bus << endl;
    else cout << "Different" << endl;
    return 0;
}
error: no match for 'operator==' (operand types are 'Duration' and 'Duration')

C++ doesn't guess what "equal" means for your class. Add a member that returns bool:

bool operator==(const Duration& o) const {
    return h == o.h && m == o.m;
}
#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
    bool operator==(const Duration& o) const {
        return h == o.h && m == o.m;
    }
};
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.hours() << "h " << d.mins() << "m";
    return out;
}

int main() {
    Duration bus(11, 15), train(4, 45);
    train = train + Duration(6, 30);
    if (bus == train) cout << "Same time: " << bus << endl;
    else cout << "Different" << endl;
    return 0;
}

Output:

Same time: 11h 15m

Because the constructor normalises, Duration(10, 75) == Duration(11, 15) is also true. Without the invariant, == would need to do the maths itself.

The != trap: each operator is its own function

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    Duration operator+(const Duration& o) const {
        return Duration(h + o.h, m + o.m);
    }
    bool operator==(const Duration& o) const {
        return h == o.h && m == o.m;
    }
};
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.hours() << "h " << d.mins() << "m";
    return out;
}

int main() {
    Duration bus(11, 15), train(4, 45);
    train = train + Duration(6, 30);
    if (bus != train) cout << "Different" << endl;
    else cout << "Same time: " << bus << endl;
    return 0;
}
error: no match for 'operator!=' (operand types are 'Duration' and 'Duration')

Writing + doesn't give you +=, and in C++17 writing == doesn't give you !=. (C++20 rewrites a != b as !(a == b) automatically, but the SyntaxPilot compiler uses C++17.) The fix is one line, written in terms of == so the two can never disagree:

bool operator!=(const Duration& o) const { return !(*this == o); }

*this means "this object itself" (episode 18 explains this).

Member or non-member?

Member Non-member
Looks like T operator+(const T& o) const T operator+(const T& a, const T& b)
a + b becomes a.operator+(b) operator+(a, b)
Left operand must be your class anything (e.g. cout, an int)
Sees private data yes no (use getters, or make it a friend, episode 18)
Typical for +, -, ==, <, +=, [], = <<, >>, and int * Money

Some operators must be members: =, [], (), ->.

Operator overloading rules

  1. a + b is just a function call: a.operator+(b) or operator+(a, b).
  2. Your object on the left → a member works; something else on the left (like cout) → a non-member.
  3. operator<< returns ostream& (so << can chain).
  4. At least one operand must be your own type: you can't change what int + int means.
  5. You can't invent new symbols (there is no ** in C++), and you can't change precedence (* still beats +), associativity or the number of operands.
  6. These can't be overloaded at all: . (member access), :: (scope), ?: (ternary), sizeof, .*.
  7. Keep the meaning natural: + should add, == should compare. An operator that surprises the reader is worse than a named function.

Common mistakes (and the real g++ messages)

Mistake Code What g++ says / what happens Fix
Using + before writing it Duration total = a + b; error: no match for 'operator+' (operand types are 'Duration' and 'Duration') write Duration operator+(const Duration& o) const
operator<< returns void void operator<<(ostream& out, const Duration& d) error: invalid operands of types 'void' and '<unresolved overloaded function type>' to binary 'operator<<' return ostream&, end with return out;
Printing a class with no operator<< cout << total; error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'Duration') a non-member operator<<
Expecting != for free if (bus != train) error: no match for 'operator!=' (operand types are 'Duration' and 'Duration') bool operator!=(...) const { return !(*this == o); }
Not normalising Duration(h + o.h, m + o.m) with a plain constructor no message: prints 10h 75m normalise in the constructor
operator<< as a member of your class ostream& operator<<(ostream& out) const it compiles, but you'd have to write total << cout make it a non-member
Returning the stream by value ostream operator<<(...) error: streams can't be copied (use of deleted function) return ostream&

Mini project: a shopping cart

A Money class stores paise as a whole number (long), so there are no floating-point rounding errors (0.1 + 0.2 is not exactly 0.3 in a double). It overloads + (add two amounts), * (price × quantity) and << (print as Rs. 45.50).

#include <iostream>
using namespace std;

class Money {
    long paise;
public:
    Money(long rs, long p) : paise(rs * 100 + p) {}
    long total() const { return paise; }
    Money operator+(const Money& o) const { return Money(0, paise + o.paise); }
    Money operator*(int qty) const { return Money(0, paise * qty); }
};
ostream& operator<<(ostream& out, const Money& x) {
    long p = x.total() % 100;
    out << "Rs. " << x.total() / 100 << (p < 10 ? ".0" : ".") << p;
    return out;
}

int main() {
    Money bill(0, 0);
    long rs, p; int qty;
    while (cin >> rs >> p >> qty) {
        Money line = Money(rs, p) * qty;
        cout << qty << " x " << Money(rs, p) << " = " << line << endl;
        bill = bill + line;
    }
    cout << "Total: " << bill << endl;
    return 0;
}

Input:

45 50 2
120 0 1
9 75 4

Output:

2 x Rs. 45.50 = Rs. 91.00
1 x Rs. 120.00 = Rs. 120.00
4 x Rs. 9.75 = Rs. 39.00
Total: Rs. 250.00

bill = bill + line; and Money(rs, p) * qty read like the shop's bill book. The (p < 10 ? ".0" : ".") part prints 9.05 rather than 9.5 for 5 paise.

Practice

  1. Add operator!= and operator< to Duration, then find the shorter of two trips.
  2. Add operator- to Money for a discount, and print the bill after a Rs. 20 discount.
  3. A Point class (x, y) with + and <<, printing (3, 7).
  4. Make operator<< return void again and read the error. Then remove << endl from that line. Does it compile now? Why?
Solutions

1. < compares total minutes. != is written using ==.

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm) : h(hh + mm / 60), m(mm % 60) {}
    int hours() const { return h; }
    int mins() const { return m; }
    bool operator==(const Duration& o) const { return h == o.h && m == o.m; }
    bool operator!=(const Duration& o) const { return !(*this == o); }
    bool operator<(const Duration& o) const { return h * 60 + m < o.h * 60 + o.m; }
};
ostream& operator<<(ostream& out, const Duration& d) {
    out << d.hours() << "h " << d.mins() << "m";
    return out;
}

int main() {
    Duration bus(11, 15), flight(1, 155);
    if (bus != flight) cout << "Different times" << endl;
    if (flight < bus) cout << "Flight is shorter: " << flight << endl;
    else cout << "Bus is shorter: " << bus << endl;
    return 0;
}

Output:

Different times
Flight is shorter: 3h 35m

2. A discount is subtraction.

#include <iostream>
using namespace std;

class Money {
    long paise;
public:
    Money(long rs, long p) : paise(rs * 100 + p) {}
    long total() const { return paise; }
    Money operator+(const Money& o) const { return Money(0, paise + o.paise); }
    Money operator-(const Money& o) const { return Money(0, paise - o.paise); }
    Money operator*(int qty) const { return Money(0, paise * qty); }
};
ostream& operator<<(ostream& out, const Money& x) {
    long p = x.total() % 100;
    out << "Rs. " << x.total() / 100 << (p < 10 ? ".0" : ".") << p;
    return out;
}

int main() {
    Money bill = Money(45, 50) * 2 + Money(120, 0);
    cout << "Bill: " << bill << endl;
    cout << "After discount: " << bill - Money(20, 0) << endl;
    return 0;
}

Output:

Bill: Rs. 211.00
After discount: Rs. 191.00

3.

#include <iostream>
using namespace std;

class Point {
    int x, y;
public:
    Point(int a, int b) : x(a), y(b) {}
    int getX() const { return x; }
    int getY() const { return y; }
    Point operator+(const Point& o) const { return Point(x + o.x, y + o.y); }
};
ostream& operator<<(ostream& out, const Point& p) {
    out << "(" << p.getX() << ", " << p.getY() << ")";
    return out;
}

int main() {
    Point a(1, 2), b(2, 5);
    cout << a << " + " << b << " = " << a + b << endl;
    return 0;
}

Output:

(1, 2) + (2, 5) = (3, 7)

4. With void, cout << total << endl; fails with invalid operands of types 'void' and '<unresolved overloaded function type>'. cout << total; alone compiles, because nothing uses the (missing) return value. The chain is what needs the ostream& back.

Quick quiz

What does this print?

#include <iostream>
using namespace std;

class Duration {
    int h, m;
public:
    Duration(int hh, int mm)
        : h(hh + mm / 60), m(mm % 60) {}
    Duration operator+(const Duration& o) const
        { return Duration(h + o.h, m + o.m); }
    void show() const { cout << h << ":" << m; }
};

int main() {
    Duration x = Duration(1, 50) + Duration(0, 20);
    x.show();
    return 0;
}
  • A. 1:70
  • B. 2:10
  • C. 1:10
  • D. Compile error
Answer

B: 2:10 (verified). operator+ builds Duration(1, 70). The constructor normalises it: 1 + 70 / 60 = 2 hours, 70 % 60 = 10 minutes.

Output:

2:10

Interview questions

  • What is operator overloading? Defining what an existing operator means for a user-defined type, by writing a function named operator@ (e.g. operator+). It's a form of compile-time polymorphism.
  • Member vs non-member operator? A member has the class object as the left operand (a.operator+(b)); a non-member takes both operands (operator+(a, b)) and is needed when the left operand isn't your class, like cout << x or 2 * money.
  • Why does operator<< return ostream&? So calls can chain: cout << a << b is (cout << a) << b. A reference, because streams can't be copied.
  • Which operators can't be overloaded? ., .*, ::, ?:, sizeof (also typeid, alignof, and the casts).
  • Which must be members? =, [], (), ->.
  • Can you change an operator's precedence or create a new operator? No. You can only give existing operators a meaning for your types; precedence, associativity and arity stay the same.
  • Why take the parameter as const T&? To avoid a copy and to promise not to change the operand. The trailing const on a member says the left operand isn't changed.
  • Does defining == give you !=? Not before C++20. In C++20 the compiler rewrites a != b to !(a == b) and supports <=> (the "spaceship" operator) for all comparisons.
  • What should + return, a value or a reference? A new value (T), because a + b creates a new result. Compound assignment (+=) changes the left operand and returns T& (*this).

Glossary

Term Plain meaning Example
Operator A symbol that does an operation on values (operands) +, ==, <<
Operand A value an operator works on in a + b, a and b
Built-in type A type C++ already knows int, double, char
User-defined type A type you create with class/struct Duration, Money
Operator overloading Giving an existing operator a meaning for your own type Duration operator+(...)
Operator function The function behind an operator, named operator + symbol operator+, operator<<
Member operator An operator function inside the class; your object is the left operand a.operator+(b)
Non-member operator An operator function outside the class with both operands as parameters operator<<(cout, total)
const reference parameter Pass without copying, and promise not to change it const Duration& o
const member function A member that doesn't change the object it's called on ... operator+(...) const
Normalise Bring a value into its standard form 10h 75m → 11h 15m
Class invariant A rule that is true for every object at all times minutes are always 0-59
Integer division Division of whole numbers that drops the remainder 75 / 60 is 1
Modulo The remainder after division 75 % 60 is 15
ostream The type of output streams like cout ostream& out
Insertion operator << used with a stream: puts a value into it cout << total
Chaining Using the result of one call as the start of the next cout << a << endl
Precedence Which operator runs first when mixed * before +
Paise 1/100 of a rupee; storing money as a whole number of paise avoids rounding errors Rs. 45.50 = 4550 paise

Summary

  • +, == and << only work on built-in types until you teach them; a + b on a Duration gives no match for 'operator+'.
  • Operator overloading: write a function named operator+; a + b becomes a.operator+(b).
  • Keep objects valid (invariants) in the constructor, so operators stay simple: 10h 75m → 11h 15m.
  • cout << x has cout on the left, so operator<< is a non-member: ostream& operator<<(ostream& out, const T& x), returning out so << can chain.
  • operator== compares; != is a separate function in C++17.
  • You can't overload operators for built-in types only, invent new symbols, or change precedence; . :: ?: sizeof can't be overloaded. Keep meanings natural.

Next episode: friend functions, static members and this. Our operator<< needed getters because it isn't a member; and what if every object needs to share one counter?