TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 8 of 18 · Free

Operator Overloading in C++ – Make Your Classes Work with +, == and <<

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Overload arithmetic and comparison operators for your own class
  • Print objects with cout by overloading <<
  • Overload +=, [] and ++ correctly, and follow the rules of overloading

You add two numbers with a + b every day. But a school bill has rupees AND paise, and a recipe has fractions like 3/4. Wouldn't it be nice to write fee + fine for your own Money class too? Operator overloading lets your classes use +, ==, << and more, just like built-in types.

What is operator overloading in C++?

An operator is a symbol like + or ==. Operator overloading means writing what that symbol does for your own class.

You write a function named operator+. Then a + b on two Money objects calls a.operator+(b) for you. The result is a new Money object; a and b do not change.

Money keeps everything in paise inside (1 rupee = 100 paise). This avoids rounding errors that double can give with money.

Try it: add a third amount, the bus fee of Rs 350.75, to the total.

🧩 C++ — you can edit this code
Output
Rs 1226.25

How do I overload == and < in C++?

Comparison operators return bool. == says whether two objects are equal. You decide what "equal" means for your class.

If you write operator<, sort can sort your objects with no lambda at all, because sort uses < by default. We use stable_sort here: it keeps students with equal marks in their original order.

In C++17, writing == does not give you != for free. Write != too, usually by calling ==.

Try it: change operator< to compare names instead of marks and run again.

🧩 C++ — you can edit this code
Output
Asha and Chetan tie? yes
Asha and Bilal differ? yes
Bilal 67
Asha 82
Chetan 82
Diya 91

💡 *this is the object the function was called on. !(*this == o) reuses == so the two can never disagree.

How do I print my own class with cout << in C++?

cout << f means operator<<(cout, f). The left side is the stream, not your object. So this operator must be a normal function outside the class, not a member.

It takes ostream& out and your object, prints into out, and returns out. Returning out is what lets you chain: cout << a << " and " << b.

Marking it friend inside the class lets this outside function read the private members.

Try it: print a fraction with a bigger numerator, like Fraction(7, 3).

🧩 C++ — you can edit this code
Output
Half: 1/2, quarter: 1/4

How do I overload +=, [] and ++ in C++?

+= changes the object itself, so it returns a reference to it: Marks& operator+=(int m). Returning *this lets you chain calls.

[] should return a reference (int&) so that report[1] = 95; changes the real value. Check the index inside, so a wrong index cannot touch other memory.

Prefix ++x is written operator++(). Postfix x++ is written operator++(int); the int is only a marker. Prefer prefix: it does not need a copy.

Try it: add the marks 72 with += and print the count and total again.

🧩 C++ — you can edit this code
Output
4 marks, second is 67
(bad index 9)

What are the rules of operator overloading in C++?

You cannot make new operators, and you cannot change how many operands one takes or its precedence. * still binds tighter than +.

A few operators cannot be overloaded at all: :: (scope), . (member), .* , ?: and sizeof.

Keep the meaning natural. + should add, not print or delete. If an operator would surprise a reader, use a named function instead.

Here * multiplies two fractions and simplifies the result with gcd (greatest common divisor) from <numeric>. Try it: multiply three fractions in one line.

🧩 C++ — you can edit this code
Output
3/4 x 2/3 = 1/2
2/4 == 1/2? yes

💡 The constructor simplifies every fraction, so 2/4 is stored as 1/2 and == can compare the parts directly.

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

#include <iostream>
using namespace std;

struct Score {
    int runs, wickets;
    Score operator+(const Score& o) const {
        return {runs + o.runs, wickets + o.wickets};
    }
};

int main() {
    Score firstHalf{86, 2}, secondHalf{74, 3};
    Score total = firstHalf + secondHalf;
    cout << total.runs << "/" << total.wickets << "\n";
    return 0;
}

Question 2. What does this print?

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

struct Train {
    string name;
    int minutesLate;
    bool operator<(const Train& o) const { return minutesLate < o.minutesLate; }
};

int main() {
    vector<Train> t = {{"Garib Rath", 40}, {"Shatabdi", 5}, {"Duronto", 20}};
    sort(t.begin(), t.end());
    cout << t[0].name << ", " << t[2].name << "\n";
    return 0;
}

Question 3. What does this print?

#include <iostream>
using namespace std;

class Counter {
    int n = 0;
public:
    Counter& operator+=(int x) { n += x; return *this; }
    int get() const { return n; }
};

int main() {
    Counter c;
    (c += 3) += 4;
    c += 10;
    cout << c.get() << "\n";
    return 0;
}

🧩 Your challenge

Write a class Time for a railway timetable, with hours (0–23) and minutes. Overload + so that Time + int adds minutes and wraps past midnight, < to compare two times, and << to print as HH:MM with two digits each. For a train leaving at 22:45 that takes 95 minutes, and a bus at 23:30, print: Departs 22:45, arrives 00:20 Bus at 23:30 leaves first? no

Expected output :
Departs 22:45, arrives 00:20
Bus at 23:30 leaves first? no
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <iostream>
using namespace std;

class Point {
    int x = 2, y = 5;
public:
    ostream& operator<<(ostream& out) {
        return out << "(" << x << ", " << y << ")";
    }
};

int main() {
    Point p;
    cout << p << "\n";
    return 0;
}

Line 14: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'Point')

✅ Right

#include <iostream>
using namespace std;

class Point {
    int x = 2, y = 5;
public:
    friend ostream& operator<<(ostream& out, const Point& p) {
        return out << "(" << p.x << ", " << p.y << ")";
    }
};

int main() {
    Point p;
    cout << p << "\n";
    return 0;
}

As a member, << would need the Point on the LEFT (p << cout). For cout << p, write a non-member (friend) function that takes ostream& first.

❌ Wrong

#include <iostream>
#include <vector>
using namespace std;

class Marks {
    vector<int> v = {50, 60};
public:
    int operator[](int i) { return v[i]; }
};

int main() {
    Marks m;
    m[0] = 75;
    cout << m[0] << "\n";
    return 0;
}

Line 13: error: expression is not assignable

✅ Right

#include <iostream>
#include <vector>
using namespace std;

class Marks {
    vector<int> v = {50, 60};
public:
    int& operator[](int i) { return v[i]; }
};

int main() {
    Marks m;
    m[0] = 75;
    cout << m[0] << "\n";
    return 0;
}

Returning int gives back a temporary copy, which cannot be assigned to. Return int& so m[0] = 75 changes the real value.

❌ Wrong

#include <iostream>
using namespace std;

class Money {
public:
    int rupees;
    Money operator+(const Money& o) {
        rupees += o.rupees;
        return *this;
    }
};

int main() {
    Money fee{500}, fine{50};
    Money total = fee + fine;
    cout << total.rupees << " " << fee.rupees << "\n";
    return 0;
}

Compiles and runs, but prints: 550 550 ⏎

✅ Right

#include <iostream>
using namespace std;

class Money {
public:
    int rupees;
    Money operator+(const Money& o) const {
        return Money{rupees + o.rupees};
    }
};

int main() {
    Money fee{500}, fine{50};
    Money total = fee + fine;
    cout << total.rupees << " " << fee.rupees << "\n";
    return 0;
}

+ must not change its operands: after a + b, a should be the same. Build and return a new object, and mark operator+ const so the compiler checks this.

📌 Remember

  • operator+ (and friends) let your class use normal symbols: a + b calls a.operator+(b).
  • +, -, *, == and < return new values or bool and should not change their operands.
  • +=, ++ and [] change or expose the object, so they return a reference.
  • operator<< for cout is a non-member (often a friend) that returns the ostream&.
  • Keep meanings natural; a few operators like :: and . cannot be overloaded.

Finished the quiz and the challenge?

Questions students ask

Which operators cannot be overloaded in C++?

The scope operator ::, the member access operators . and .*, the conditional ?: and sizeof cannot be overloaded. Almost all others, including [], (), << and ->, can.

Should an operator be a member function or a friend?

Operators that change the object, like += and [], are usually members. Operators whose left side is not your class, like cout << obj, must be non-members, often friends. Symmetric ones like + are often non-members too.

Does Java have operator overloading?

No, Java does not let you overload operators for your own classes. Python does, with special methods like __add__. C++ offers it with operator functions, as in this lesson.

What is a friend function in C++?

A friend function is a normal function that a class allows to read its private members. You declare it inside the class with the word friend. Use it sparingly, mostly for operators like <<.