DEV Community

Cover image for C++ Operator Overloading Explained from Zero — A Complete Beginner-Friendly Guide with a `Time` Class
Poushmita Paul
Poushmita Paul

Posted on

C++ Operator Overloading Explained from Zero — A Complete Beginner-Friendly Guide with a `Time` Class

A step-by-step guide where we don't just learn what the code does — we understand why every word, symbol, parameter, and line of code is used.


👋 Why I Created This Guide

Recently, a friend asked me to help her understand Operator Overloading in C++ because she was having difficulty understanding it from her training.

When I looked at the code, I realized something important.

The problem wasn't necessarily the Operator Overloading itself.

The problem was that many small C++ concepts were being used together.

For example, a beginner may see:

Time Time::operator+(const Time &t)
Enter fullscreen mode Exit fullscreen mode

and immediately have questions:

  • ❓ Why are there two Times?
  • ❓ What does Time:: mean?
  • ❓ Why is the function called operator+?
  • ❓ What does const mean?
  • ❓ What does & mean?
  • ❓ What is t?
  • ❓ Where did the first object go?
  • ❓ Why do we need temp?
  • ❓ Why are we returning Time?
  • ❓ What is this?
  • ❓ Why does postfix ++ have int?
  • ❓ Why are ostream and istream used?
  • ❓ Why are << and >> used?

If these small questions aren't answered, it becomes very easy to memorize the syntax without understanding the concept.

So in this article, I want to explain Operator Overloading the way I would explain it to a friend sitting beside me.

The goal is not:

❌ "Memorize this code."

The goal is:

"Look at the code and understand why every part is there."


📚 What We Will Learn

By the end of this article, you should understand:

  • Classes and objects
  • Operators and operands
  • Unary vs Binary operators
  • Operator Overloading
  • Member operator functions
  • operator+()
  • operator-()
  • operator=()
  • Prefix ++
  • Postfix ++
  • Prefix --
  • Postfix --
  • Why postfix operators use a dummy int
  • this
  • *this
  • const
  • References using &
  • Return types such as Time and Time&
  • ostream
  • istream
  • operator<<
  • operator>>
  • Time addition
  • Time subtraction
  • Borrowing
  • Time normalization
  • How C++ can be thought of as translating operator expressions into function calls

🧱 Part 1 — Before Operator Overloading

Before learning Operator Overloading, let's understand the object we are going to use.

We will create a class called Time.

1. What Is a Class?

Consider this:

class Time
{
    int hours;
    int minutes;
};
Enter fullscreen mode Exit fullscreen mode

If you've already studied classes, this may look simple.

But let's slow down.

What does class mean?

class is a C++ keyword used to create a class.

A simple way to understand a class is to think of it as a blueprint.

Imagine an architect creates a blueprint for a house.

The blueprint describes:

  • rooms
  • doors
  • windows
  • structure

But the blueprint itself is not the actual house.

Similarly, our Time class is a blueprint.

It tells us:

"A Time object will contain information related to hours and minutes."

Visualize it like this:

             Time
        ┌───────────────┐
        │   BLUEPRINT   │
        │               │
        │    hours      │
        │    minutes    │
        └───────────────┘
Enter fullscreen mode Exit fullscreen mode

2. What Are hours and minutes?

Inside the class we have:

int hours;
int minutes;
Enter fullscreen mode Exit fullscreen mode

What is int?

int is a C++ data type used for storing whole numbers.

For example:

int age = 21;
Enter fullscreen mode Exit fullscreen mode

Here:

  • int → data type
  • age → variable name
  • 21 → value

Similarly:

int hours;
int minutes;
Enter fullscreen mode Exit fullscreen mode

means our Time object will contain two integer variables:

hours
minutes
Enter fullscreen mode Exit fullscreen mode

For example:

hours   = 2
minutes = 40
Enter fullscreen mode Exit fullscreen mode

represents:

2 hours 40 minutes


3. What Is an Object?

We have created our blueprint:

class Time
{
    int hours;
    int minutes;
};
Enter fullscreen mode Exit fullscreen mode

But we still haven't created an actual Time object.

To create one:

Time t;
Enter fullscreen mode Exit fullscreen mode

Let's read this from left to right:

Time        t
 ↓          ↓
type       name
Enter fullscreen mode Exit fullscreen mode

Time is the class type we created.

t is the name of the object.

So:

Time t;
Enter fullscreen mode Exit fullscreen mode

simply means:

Create an object named t whose type is Time.

You can visualize it like this:

             Time class
          ┌──────────────┐
          │   blueprint  │
          │              │
          │    hours     │
          │    minutes   │
          └──────┬───────┘
                 │
            create object
                 ↓
          ┌──────────────┐
          │      t       │
          ├──────────────┤
          │    hours     │
          │    minutes   │
          └──────────────┘
Enter fullscreen mode Exit fullscreen mode

4. Class vs Object

This distinction is extremely important.

🟦 Class

A class is the blueprint or definition.

class Time
{
    int hours;
    int minutes;
};
Enter fullscreen mode Exit fullscreen mode

🟩 Object

An object is an actual object created from that class.

Time t;
Enter fullscreen mode Exit fullscreen mode

We can create many objects from the same class:

Time t1;
Time t2;
Time t3;
Enter fullscreen mode Exit fullscreen mode

Visual:

                 Time class
              /      |      \
             ↓       ↓       ↓
          ┌─────┐ ┌─────┐ ┌─────┐
          │ t1  │ │ t2  │ │ t3  │
          └─────┘ └─────┘ └─────┘
Enter fullscreen mode Exit fullscreen mode

All three objects are created from the same class.

They have the same structure, but their values can be different.

For example:

t1 → 2 hours 40 minutes

t2 → 1 hour 30 minutes

t3 → 5 hours 10 minutes
Enter fullscreen mode Exit fullscreen mode

5. Objects Can Also Use Functions

A class can contain variables as well as functions.

For example:

class Time
{
public:

    int hours;
    int minutes;

    void display()
    {
        cout << hours << " hours "
             << minutes << " minutes";
    }
};
Enter fullscreen mode Exit fullscreen mode

Now:

Time t;
Enter fullscreen mode Exit fullscreen mode

creates an object called t.

That object can call the function:

t.display();
Enter fullscreen mode Exit fullscreen mode

This means:

Call the display() function for object t.

Keep this idea in mind.

Later we will see:

t1.operator+(t2);
Enter fullscreen mode Exit fullscreen mode

The same basic idea is involved:

An object can call a member function that belongs to its class.


⚙️ Part 2 — Understanding Operators

Now let's move to operators.

You have already used operators many times.

For example:

int a = 10;
int b = 20;

int c = a + b;
Enter fullscreen mode Exit fullscreen mode

Look at:

a + b
Enter fullscreen mode Exit fullscreen mode

There are three things:

a       +       b
↑       ↑       ↑
operand operator operand
Enter fullscreen mode Exit fullscreen mode

The + is the operator.

a and b are the operands.


6. What Is an Operand?

An operand is the value or object on which an operator works.

For:

10 + 20
Enter fullscreen mode Exit fullscreen mode

the operator is:

+
Enter fullscreen mode Exit fullscreen mode

and the operands are:

10
20
Enter fullscreen mode Exit fullscreen mode

Visual:

             +
            / \
           /   \
         10     20
         ↑       ↑
      operand  operand
Enter fullscreen mode Exit fullscreen mode

7. What Does the + Operator Already Know?

C++ already knows how to use + with built-in data types.

For example:

10 + 20
Enter fullscreen mode Exit fullscreen mode

produces:

30
Enter fullscreen mode Exit fullscreen mode

C++ already knows rules for operations such as:

int + int
float + float
double + double
Enter fullscreen mode Exit fullscreen mode

But now we have created our own type:

Time
Enter fullscreen mode Exit fullscreen mode

And this creates a problem.


❓ Part 3 — The Problem We Need to Solve

Suppose we have:

Time t1;
Time t2;
Enter fullscreen mode Exit fullscreen mode

and:

t1 = 2 hours 40 minutes

t2 = 1 hour 30 minutes
Enter fullscreen mode Exit fullscreen mode

Now suppose we want to write:

Time t3 = t1 + t2;
Enter fullscreen mode Exit fullscreen mode

What should + do?

C++ knows:

10 + 20
Enter fullscreen mode Exit fullscreen mode

But C++ does not automatically know what this means:

t1 + t2
Enter fullscreen mode Exit fullscreen mode

when t1 and t2 are Time objects.

We need to tell C++ what + should mean for our Time class.

And that is where:

⭐ Operator Overloading

comes in.


8. What Is Operator Overloading?

A simple definition is:

Operator Overloading means giving an existing C++ operator a special meaning when it is used with objects of our own class.

Notice an important point:

We are not creating a new operator.

The operator already exists.

For example:

+
-
=
++
--
<<
>>
Enter fullscreen mode Exit fullscreen mode

We are simply teaching C++:

"When this operator is used with my Time objects, perform this operation."

For example:

t1 + t2
Enter fullscreen mode Exit fullscreen mode

can be made to mean:

Add hours
   +
Add minutes
   +
Convert extra minutes into hours
Enter fullscreen mode Exit fullscreen mode

9. Why Is Operator Overloading Useful?

Without Operator Overloading, we could create a normal function:

Time addTime(Time t1, Time t2);
Enter fullscreen mode Exit fullscreen mode

and then:

Time t3 = addTime(t1, t2);
Enter fullscreen mode Exit fullscreen mode

That works.

But with Operator Overloading, we can write:

Time t3 = t1 + t2;
Enter fullscreen mode Exit fullscreen mode

This looks much more natural.

We are making our custom objects behave more like the built-in types we already know.


🔢 Part 4 — Unary vs Binary Operators

Before writing the operator functions, we need to understand one simple question:

How many operands are involved?


Binary Operator

A binary operator works with two operands.

Example:

t1 + t2;
Enter fullscreen mode Exit fullscreen mode

Visual:

        +
       / \
     t1   t2
Enter fullscreen mode Exit fullscreen mode

There are two operands.

Therefore:

2 operands → Binary operator

Other examples:

t1 - t2;
t1 = t2;
Enter fullscreen mode Exit fullscreen mode

Unary Operator

A unary operator works with one operand.

Example:

++t1;
Enter fullscreen mode Exit fullscreen mode

Visual:

       ++
        |
       t1
Enter fullscreen mode Exit fullscreen mode

There is only one operand.

Therefore:

1 operand → Unary operator

Examples:

++t1;
--t1;
t1++;
t1--;
Enter fullscreen mode Exit fullscreen mode

🧠 Easy Rule

Remember this:

┌─────────────────────────┐
│  2 operands → BINARY    │
│  1 operand  → UNARY     │
└─────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

That's enough to classify the operators we are using.


➕ Part 5 — operator+()

Now let's finally overload +.

We want this:

Time t3 = t1 + t2;
Enter fullscreen mode Exit fullscreen mode

to work.

So we define:

Time Time::operator+(const Time &t)
{
    Time temp;

    temp.hours = hours + t.hours;
    temp.minutes = minutes + t.minutes;

    temp.hours = temp.hours + temp.minutes / 60;
    temp.minutes = temp.minutes % 60;

    return temp;
}
Enter fullscreen mode Exit fullscreen mode

Don't try to memorize this.

We are going to take it apart piece by piece.


10. Understanding the Function Header

Look at:

Time Time::operator+(const Time &t)
Enter fullscreen mode Exit fullscreen mode

Break it into parts:

Time        Time::        operator+        (const Time &t)
  ↑            ↑              ↑                   ↑
return      belongs        operator            parameter
 type       to Time        being used           object
Enter fullscreen mode Exit fullscreen mode

Now let's understand every part.


11. The First Time

Time Time::operator+
Enter fullscreen mode Exit fullscreen mode

The first Time is the return type.

What is a return type?

A function can produce a result.

For example:

int add(int a, int b)
{
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

The result is an integer.

Therefore:

int
Enter fullscreen mode Exit fullscreen mode

is the return type.

Our operator function returns:

Time
Enter fullscreen mode Exit fullscreen mode

Why?

Because:

Time + Time
Enter fullscreen mode Exit fullscreen mode

produces another Time.

For example:

     2 hours 40 minutes
   + 1 hour 30 minutes
   -------------------
     4 hours 10 minutes
Enter fullscreen mode Exit fullscreen mode

The result is still a Time.

Therefore:

Time
Enter fullscreen mode Exit fullscreen mode

is the return type.


12. What Does Time:: Mean?

The symbol:

::
Enter fullscreen mode Exit fullscreen mode

is called the scope resolution operator.

It tells C++ which class something belongs to.

So:

Time::operator+
Enter fullscreen mode Exit fullscreen mode

means:

The operator+ function belonging to the Time class.

Think:

Time
  ↓
class
  ↓
operator+
  ↓
belongs to Time
Enter fullscreen mode Exit fullscreen mode

13. What Does operator+ Mean?

This part:

operator+
Enter fullscreen mode Exit fullscreen mode

means:

We are defining the behavior of the + operator.

Similarly:

operator-
Enter fullscreen mode Exit fullscreen mode

defines -.

operator=
Enter fullscreen mode Exit fullscreen mode

defines =.

operator++
Enter fullscreen mode Exit fullscreen mode

defines ++.

And so on.


14. Understanding (const Time &t)

Now look at:

(const Time &t)
Enter fullscreen mode Exit fullscreen mode

This is the parameter list.

A parameter is information that a function receives.

For example:

int add(int a, int b)
Enter fullscreen mode Exit fullscreen mode

has:

a
b
Enter fullscreen mode Exit fullscreen mode

as parameters.

Our function receives:

const Time &t
Enter fullscreen mode Exit fullscreen mode

Let's understand each piece.


15. What Does Time Mean Here?

Look at:

Time t
Enter fullscreen mode Exit fullscreen mode

This means:

t is of type Time.

Remember:

Time t1;
Enter fullscreen mode Exit fullscreen mode

means:

Create a Time object called t1.

Similarly, inside our function:

Time t
Enter fullscreen mode Exit fullscreen mode

means:

t refers to a Time object received by the function.


16. What Does & Mean?

Here:

Time &t
Enter fullscreen mode Exit fullscreen mode

the & means reference.

A reference is another name or alias for an existing object.

Instead of creating a completely separate copy of the object, the parameter refers to an existing object.

For our expression:

t1 + t2;
Enter fullscreen mode Exit fullscreen mode

we can think of the call as:

t1.operator+(t2);
Enter fullscreen mode Exit fullscreen mode

Inside the function:

t1
 ↓
current object

t2
 ↓
parameter t
Enter fullscreen mode Exit fullscreen mode

So t refers to the second object.


17. What Does const Mean?

Now we have:

const Time &t
Enter fullscreen mode Exit fullscreen mode

const means:

We promise not to modify the object through this reference.

Why?

Because while calculating:

t1 + t2
Enter fullscreen mode Exit fullscreen mode

we only need to read t2.

We don't want addition to change t2.

So:

const Time &t
Enter fullscreen mode Exit fullscreen mode

can be understood as:

"Give me a reference to another Time object. I only want to read it, not modify it."


⭐ 18. Where Did t1 Go?

This is one of the most important ideas in understanding member operator functions.

Suppose we write:

t1 + t2;
Enter fullscreen mode Exit fullscreen mode

Because operator+ is a member function of Time, we can think of it as:

t1.operator+(t2);
Enter fullscreen mode Exit fullscreen mode

Now everything becomes easier to understand.

t1.operator+(t2)
 ↑              ↑
 |              |
current         parameter
object          t
Enter fullscreen mode Exit fullscreen mode

So:

t1 → current object

t2 → parameter t
Enter fullscreen mode Exit fullscreen mode

Inside the function:

hours
Enter fullscreen mode Exit fullscreen mode

means the hours belonging to the current object.

So we can mentally think:

hours
Enter fullscreen mode Exit fullscreen mode

as:

t1.hours
Enter fullscreen mode Exit fullscreen mode

And:

t.hours
Enter fullscreen mode Exit fullscreen mode

means:

t2.hours
Enter fullscreen mode Exit fullscreen mode

This mental model is extremely important.


🧮 19. Let's Actually Add Two Times

Suppose:

t1 = 2 hours 40 minutes

t2 = 1 hour 30 minutes
Enter fullscreen mode Exit fullscreen mode

We want:

       2 h 40 m
     + 1 h 30 m
     -----------
       4 h 10 m
Enter fullscreen mode Exit fullscreen mode

First we add the hours.

temp.hours = hours + t.hours;
Enter fullscreen mode Exit fullscreen mode

The current object's hours:

t1.hours = 2
Enter fullscreen mode Exit fullscreen mode

The parameter object's hours:

t2.hours = 1
Enter fullscreen mode Exit fullscreen mode

Therefore:

2 + 1 = 3
Enter fullscreen mode Exit fullscreen mode

So:

temp.hours = 3
Enter fullscreen mode Exit fullscreen mode

20. Adding the Minutes

Next:

temp.minutes = minutes + t.minutes;
Enter fullscreen mode Exit fullscreen mode

We have:

t1.minutes = 40

t2.minutes = 30
Enter fullscreen mode Exit fullscreen mode

Therefore:

40 + 30 = 70
Enter fullscreen mode Exit fullscreen mode

Now:

temp = 3 hours 70 minutes
Enter fullscreen mode Exit fullscreen mode

But this isn't the normal way we represent time.

We normally want minutes to be:

0 to 59
Enter fullscreen mode Exit fullscreen mode

So we need to convert the extra minutes.


🔄 21. What Is Normalization?

We can call this process normalization.

Normalization simply means:

Convert a value into its proper or standard form.

For example:

3 hours 70 minutes
Enter fullscreen mode Exit fullscreen mode

can be converted to:

4 hours 10 minutes
Enter fullscreen mode Exit fullscreen mode

because:

70 minutes = 1 hour 10 minutes
Enter fullscreen mode Exit fullscreen mode

22. Why Do We Use / 60?

The code says:

temp.hours = temp.hours + temp.minutes / 60;
Enter fullscreen mode Exit fullscreen mode

Suppose:

temp.minutes = 70
Enter fullscreen mode Exit fullscreen mode

Then:

70 / 60 = 1
Enter fullscreen mode Exit fullscreen mode

Because these are integers, this is integer division.

We are interested in how many complete hours are contained inside 70 minutes.

The answer is:

1 complete hour
Enter fullscreen mode Exit fullscreen mode

So:

3 hours + 1 hour
=
4 hours
Enter fullscreen mode Exit fullscreen mode

23. Why Do We Use % 60?

Next:

temp.minutes = temp.minutes % 60;
Enter fullscreen mode Exit fullscreen mode

The % operator gives the remainder after division.

For example:

70 % 60 = 10
Enter fullscreen mode Exit fullscreen mode

So:

70 minutes
Enter fullscreen mode Exit fullscreen mode

contains:

1 complete hour
+
10 minutes remaining
Enter fullscreen mode Exit fullscreen mode

Therefore:

4 hours 10 minutes
Enter fullscreen mode Exit fullscreen mode

is our final answer.


24. Why Do We Create temp?

Look at:

Time temp;
Enter fullscreen mode Exit fullscreen mode

Why are we creating another object?

Because we need a separate object to store the result.

We don't want:

t1 = 2:40

t2 = 1:30
Enter fullscreen mode Exit fullscreen mode

to be changed when we calculate:

t1 + t2
Enter fullscreen mode Exit fullscreen mode

Instead:

        t1                 t2
        │                   │
       2:40                1:30
        \                   /
         \                 /
          \               /
            operator+
                 |
                 ↓
               temp
                 |
                4:10
Enter fullscreen mode Exit fullscreen mode

So:

Time temp;
Enter fullscreen mode Exit fullscreen mode

means:

Create a temporary Time object that we can use to build the result.


25. What Does return temp Mean?

At the end:

return temp;
Enter fullscreen mode Exit fullscreen mode

means:

Give the calculated Time object back to the code that called the function.

Remember:

Time t3 = t1 + t2;
Enter fullscreen mode Exit fullscreen mode

The flow is:

t1 + t2
   ↓
operator+()
   ↓
create temp
   ↓
calculate 4:10
   ↓
return temp
   ↓
t3 receives the result
Enter fullscreen mode Exit fullscreen mode

So:

t3 = 4 hours 10 minutes
Enter fullscreen mode Exit fullscreen mode

🔍 26. Complete operator+() Flow

The expression:

Time t3 = t1 + t2;
Enter fullscreen mode Exit fullscreen mode

can be mentally understood as:

Time t3 = t1.operator+(t2);
Enter fullscreen mode Exit fullscreen mode

Then:

t1
 ↓
current object

t2
 ↓
parameter t

operator+
 ↓
create temp
 ↓
add hours
 ↓
add minutes
 ↓
convert extra minutes
 ↓
return temp
 ↓
t3
Enter fullscreen mode Exit fullscreen mode

If this flow is clear, you already understand the core idea of Operator Overloading.


➖ Part 6 — operator-()

Now let's understand subtraction.

Time Time::operator-(const Time &t)
{
    Time temp;

    temp.hours = hours;
    temp.minutes = minutes;

    if (temp.minutes < t.minutes)
    {
        temp.hours--;
        temp.minutes = temp.minutes + 60;
    }

    temp.hours = temp.hours - t.hours;
    temp.minutes = temp.minutes - t.minutes;

    return temp;
}
Enter fullscreen mode Exit fullscreen mode

Most of this is already familiar.

The main new idea is:

Borrowing


27. Why Is - Binary?

Look at:

t1 - t2;
Enter fullscreen mode Exit fullscreen mode

There are two operands:

t1     -     t2
↑            ↑
operand    operand
Enter fullscreen mode Exit fullscreen mode

Therefore:

- is a binary operator.


28. Why Do We Need Borrowing?

Suppose:

t1 = 3 hours 20 minutes

t2 = 1 hour 40 minutes
Enter fullscreen mode Exit fullscreen mode

We want:

3 h 20 m
-1 h 40 m
Enter fullscreen mode Exit fullscreen mode

But:

20 - 40
Enter fullscreen mode Exit fullscreen mode

doesn't give us a valid positive minute value.

So we borrow one hour.

Remember:

1 hour = 60 minutes
Enter fullscreen mode Exit fullscreen mode

Therefore:

3 hours 20 minutes
Enter fullscreen mode Exit fullscreen mode

becomes:

2 hours 80 minutes
Enter fullscreen mode Exit fullscreen mode

Now:

80 - 40 = 40 minutes
Enter fullscreen mode Exit fullscreen mode

and:

2 - 1 = 1 hour
Enter fullscreen mode Exit fullscreen mode

Final:

1 hour 40 minutes
Enter fullscreen mode Exit fullscreen mode

29. The Borrowing Code

if (temp.minutes < t.minutes)
{
    temp.hours--;
    temp.minutes = temp.minutes + 60;
}
Enter fullscreen mode Exit fullscreen mode

Let's read it like a human.

First:

if (temp.minutes < t.minutes)
Enter fullscreen mode Exit fullscreen mode

means:

If the minutes we currently have are smaller than the minutes we want to subtract...

Then:

temp.hours--;
Enter fullscreen mode Exit fullscreen mode

means:

Take one hour away.

For example:

3 hours
↓
2 hours
Enter fullscreen mode Exit fullscreen mode

Then:

temp.minutes = temp.minutes + 60;
Enter fullscreen mode Exit fullscreen mode

means:

Convert that borrowed hour into 60 minutes.

So:

20 minutes + 60 minutes
=
80 minutes
Enter fullscreen mode Exit fullscreen mode

Now the subtraction can continue.


30. Complete Subtraction

After borrowing:

temp.hours = temp.hours - t.hours;
temp.minutes = temp.minutes - t.minutes;
Enter fullscreen mode Exit fullscreen mode

For:

2 h 80 m
-1 h 40 m
Enter fullscreen mode Exit fullscreen mode

we get:

2 - 1 = 1 hour

80 - 40 = 40 minutes
Enter fullscreen mode Exit fullscreen mode

Final result:

1 hour 40 minutes
Enter fullscreen mode Exit fullscreen mode

🟰 Part 7 — Assignment Operator =

Now let's understand:

t1 = t2;
Enter fullscreen mode Exit fullscreen mode

This means:

Copy the data from t2 into t1.

We can overload it:

Time& Time::operator=(const Time &t)
{
    if (this != &t)
    {
        hours = t.hours;
        minutes = t.minutes;
    }

    return *this;
}
Enter fullscreen mode Exit fullscreen mode

31. Why Is = Binary?

Look at:

t1 = t2;
Enter fullscreen mode Exit fullscreen mode

There are two operands:

t1     =     t2
↑            ↑
operand    operand
Enter fullscreen mode Exit fullscreen mode

Therefore:

= is a binary operator.


🧭 32. What Does this Mean?

Now we encounter:

this
Enter fullscreen mode Exit fullscreen mode

Inside a member function, this is a pointer to the current object.

Suppose:

t1 = t2;
Enter fullscreen mode Exit fullscreen mode

is being handled by:

operator=
Enter fullscreen mode Exit fullscreen mode

Then:

current object → t1

other object   → t2
Enter fullscreen mode Exit fullscreen mode

So:

this
 ↓
t1
Enter fullscreen mode Exit fullscreen mode

In simple words:

this tells us which object is currently calling the member function.


33. What Does *this Mean?

If:

this
Enter fullscreen mode Exit fullscreen mode

is a pointer to the current object, then:

*this
Enter fullscreen mode Exit fullscreen mode

means the actual current object.

Think:

this
 ↓
address of current object

*this
 ↓
actual current object
Enter fullscreen mode Exit fullscreen mode

Therefore:

return *this;
Enter fullscreen mode Exit fullscreen mode

means:

Return the current object.


34. Why Do We Check this != &t?

The code contains:

if (this != &t)
Enter fullscreen mode Exit fullscreen mode

This checks for self-assignment.

For example:

t1 = t1;
Enter fullscreen mode Exit fullscreen mode

Here the left and right objects are the same.

We don't need to copy an object onto itself.

So the condition asks:

"Is the current object different from the object being assigned?"

If yes, perform the copy.


35. Why Does operator= Return Time&?

Notice:

Time&
Enter fullscreen mode Exit fullscreen mode

instead of:

Time
Enter fullscreen mode Exit fullscreen mode

The & means the function returns a reference to the existing Time object.

Returning a reference allows assignment expressions to behave naturally and supports expressions such as:

t1 = t2 = t3;
Enter fullscreen mode Exit fullscreen mode

For a beginner, remember:

Time& means we return the existing Time object by reference instead of creating another separate object.


⬆️ Part 8 — Prefix ++

Now let's move to unary operators.

Suppose:

t1 = 2 hours 59 minutes
Enter fullscreen mode Exit fullscreen mode

We want:

++t1;
Enter fullscreen mode Exit fullscreen mode

to increase the time by one minute.

We define:

Time& Time::operator++()
{
    minutes++;

    if (minutes >= 60)
    {
        minutes = 0;
        hours++;
    }

    return *this;
}
Enter fullscreen mode Exit fullscreen mode

36. Why Is ++ Unary?

Look at:

++t1;
Enter fullscreen mode Exit fullscreen mode

Visual:

       ++
        |
       t1
Enter fullscreen mode Exit fullscreen mode

Only one operand exists.

Therefore:

++ is a unary operator.


37. What Does minutes++ Mean?

Inside the function:

minutes++;
Enter fullscreen mode Exit fullscreen mode

means:

Increase the current object's minutes by one.

If:

minutes = 40
Enter fullscreen mode Exit fullscreen mode

then:

minutes = 41
Enter fullscreen mode Exit fullscreen mode

If:

minutes = 59
Enter fullscreen mode Exit fullscreen mode

then:

minutes = 60
Enter fullscreen mode Exit fullscreen mode

But normal time representation doesn't keep 60 minutes.

So we need:

if (minutes >= 60)
Enter fullscreen mode Exit fullscreen mode

38. What Happens at 60 Minutes?

If:

minutes = 60
Enter fullscreen mode Exit fullscreen mode

we do:

minutes = 0;
hours++;
Enter fullscreen mode Exit fullscreen mode

So:

2 hours 60 minutes
Enter fullscreen mode Exit fullscreen mode

becomes:

3 hours 0 minutes
Enter fullscreen mode Exit fullscreen mode

Therefore:

2:59
 ↓
++t1
 ↓
3:00
Enter fullscreen mode Exit fullscreen mode

39. What Is Prefix?

Prefix means the operator appears before the object:

++t1;
Enter fullscreen mode Exit fullscreen mode

The basic idea is:

CHANGE FIRST
     ↓
USE NEW VALUE
Enter fullscreen mode Exit fullscreen mode

For example:

Before → 2:59

++t1

After  → 3:00
Enter fullscreen mode Exit fullscreen mode

So prefix returns the updated object.

That's why we use:

return *this;
Enter fullscreen mode Exit fullscreen mode

⬆️ Part 9 — Postfix ++

Now look at:

t1++;
Enter fullscreen mode Exit fullscreen mode

It is also unary, but its behavior is different.

The implementation is:

Time Time::operator++(int)
{
    Time temp = *this;

    minutes++;

    if (minutes >= 60)
    {
        minutes = 0;
        hours++;
    }

    return temp;
}
Enter fullscreen mode Exit fullscreen mode

40. Why Does Postfix Have int?

This is one of the most confusing parts for beginners.

Compare:

operator++()
Enter fullscreen mode Exit fullscreen mode

and:

operator++(int)
Enter fullscreen mode Exit fullscreen mode

The int is a dummy parameter.

It is used to distinguish the two forms.

operator++()
      ↓
   PREFIX

operator++(int)
      ↓
  POSTFIX
Enter fullscreen mode Exit fullscreen mode

The int is not used to perform the increment.

It exists so C++ can distinguish prefix and postfix versions.


41. Why Do We Need temp for Postfix?

Suppose:

t1 = 2:59
Enter fullscreen mode Exit fullscreen mode

When we write:

t1++;
Enter fullscreen mode Exit fullscreen mode

postfix means:

Use the old value first, then change the object.

So first:

Time temp = *this;
Enter fullscreen mode Exit fullscreen mode

Remember:

*this
Enter fullscreen mode Exit fullscreen mode

means the current object.

Therefore:

temp = 2:59
t1   = 2:59
Enter fullscreen mode Exit fullscreen mode

Then we increment the original object:

t1 = 3:00
Enter fullscreen mode Exit fullscreen mode

But postfix needs to return the old value.

So:

return temp;
Enter fullscreen mode Exit fullscreen mode

returns:

2:59
Enter fullscreen mode Exit fullscreen mode

Final situation:

Returned value = 2:59

Current t1     = 3:00
Enter fullscreen mode Exit fullscreen mode

42. Prefix vs Postfix

This is one of the most important things to remember.

Prefix

++t1;
Enter fullscreen mode Exit fullscreen mode
OLD VALUE
    ↓
CHANGE
    ↓
NEW VALUE
    ↓
RETURN NEW VALUE
Enter fullscreen mode Exit fullscreen mode

Postfix

t1++;
Enter fullscreen mode Exit fullscreen mode
OLD VALUE
    ↓
SAVE OLD VALUE
    ↓
CHANGE ORIGINAL
    ↓
RETURN OLD VALUE
Enter fullscreen mode Exit fullscreen mode

🧠 Easy memory trick

Prefix → change first

Postfix → save/use old value first


⬇️ Part 10 — Prefix --

The same basic idea applies to decrement.

Time& Time::operator--()
{
    minutes--;

    if (minutes < 0)
    {
        minutes = 59;
        hours--;
    }

    return *this;
}
Enter fullscreen mode Exit fullscreen mode

Suppose:

t1 = 3:00
Enter fullscreen mode Exit fullscreen mode

Then:

--t1;
Enter fullscreen mode Exit fullscreen mode

does:

3:00
 ↓
minutes becomes -1
 ↓
borrow from hour
 ↓
minutes = 59
hours = 2
 ↓
2:59
Enter fullscreen mode Exit fullscreen mode

43. Why Do We Check minutes < 0?

Normally minutes should stay between:

0 and 59
Enter fullscreen mode Exit fullscreen mode

If:

minutes = 0
Enter fullscreen mode Exit fullscreen mode

and we subtract one:

minutes = -1
Enter fullscreen mode Exit fullscreen mode

That's not a valid minute value.

So we convert:

3:00
Enter fullscreen mode Exit fullscreen mode

into:

2:59
Enter fullscreen mode Exit fullscreen mode

This is essentially the reverse idea of carrying an extra hour during addition.


⬇️ Part 11 — Postfix --

The postfix version is:

Time Time::operator--(int)
{
    Time temp = *this;

    minutes--;

    if (minutes < 0)
    {
        minutes = 59;
        hours--;
    }

    return temp;
}
Enter fullscreen mode Exit fullscreen mode

Again:

t1--
 ↓
save old value
 ↓
decrement original
 ↓
return old value
Enter fullscreen mode Exit fullscreen mode

Exactly the same pattern as postfix ++.


44. ++ and -- Summary

Expression Type Meaning
++t1 Unary Prefix increment
t1++ Unary Postfix increment
--t1 Unary Prefix decrement
t1-- Unary Postfix decrement

Remember:

Prefix:
change first → return new value

Postfix:
save old value → change → return old value
Enter fullscreen mode Exit fullscreen mode

🖨️ Part 12 — Output Operator <<

Now let's understand one of the most confusing parts.

We already know:

cout << 10;
Enter fullscreen mode Exit fullscreen mode

prints:

10
Enter fullscreen mode Exit fullscreen mode

But what happens with:

Time t1;

cout << t1;
Enter fullscreen mode Exit fullscreen mode

C++ doesn't automatically know how to print our custom Time object.

So we define what << should do for Time.

ostream& operator<<(ostream &out, const Time &t)
{
    out << t.hours << " hours "
        << t.minutes << " minutes";

    return out;
}
Enter fullscreen mode Exit fullscreen mode

45. What Does cout << t1 Mean?

Think of:

cout << t1;
Enter fullscreen mode Exit fullscreen mode

as:

       <<
      /  \
   cout   t1
Enter fullscreen mode Exit fullscreen mode

There are two operands:

cout
t1
Enter fullscreen mode Exit fullscreen mode

But there is an important difference from our earlier operators.

The left operand is:

cout
Enter fullscreen mode Exit fullscreen mode

not:

Time
Enter fullscreen mode Exit fullscreen mode

That is why stream operators are commonly implemented as non-member functions.


46. What Is a Non-Member Function?

A non-member function is simply a function that does not belong to the class as a member function.

Our earlier function was:

Time Time::operator+(...)
Enter fullscreen mode Exit fullscreen mode

Notice:

Time::
Enter fullscreen mode Exit fullscreen mode

So it belongs to the Time class.

But:

ostream& operator<<(...)
Enter fullscreen mode Exit fullscreen mode

doesn't have:

Time::
Enter fullscreen mode Exit fullscreen mode

before it.

So it is a non-member function.

Why?

Because:

cout << t1;
Enter fullscreen mode Exit fullscreen mode

has:

left operand  → cout
right operand → t1
Enter fullscreen mode Exit fullscreen mode

The left operand isn't a Time object.


47. What Is ostream?

ostream means:

Output Stream

cout is an output stream.

Therefore:

ostream &out
Enter fullscreen mode Exit fullscreen mode

means:

out is a reference to an output stream.

Inside the function:

out << t.hours;
Enter fullscreen mode Exit fullscreen mode

means:

Send the hours to the output stream.


48. Why Is const Time &t Used for Output?

We have:

const Time &t
Enter fullscreen mode Exit fullscreen mode

because printing the object should only read its values.

We don't want:

cout << t1;
Enter fullscreen mode Exit fullscreen mode

to change:

t1.hours
t1.minutes
Enter fullscreen mode Exit fullscreen mode

So:

OUTPUT
  ↓
read object
  ↓
don't modify it
  ↓
const Time&
Enter fullscreen mode Exit fullscreen mode

49. Why Do We Return out?

At the end:

return out;
Enter fullscreen mode Exit fullscreen mode

This allows output chaining.

For example:

cout << t1 << t2;
Enter fullscreen mode Exit fullscreen mode

After printing t1, the stream is returned, allowing the next operation:

<< t2
Enter fullscreen mode Exit fullscreen mode

That's why stream output operators commonly return:

ostream&
Enter fullscreen mode Exit fullscreen mode

⌨️ Part 13 — Input Operator >>

Now let's look at:

cin >> t1;
Enter fullscreen mode Exit fullscreen mode

We want the user to enter a time and store it inside the Time object.

So we overload >>:

istream& operator>>(istream &in, Time &t)
{
    cout << "Enter hours: ";
    in >> t.hours;

    cout << "Enter minutes: ";
    in >> t.minutes;

    t.hours = t.hours + t.minutes / 60;
    t.minutes = t.minutes % 60;

    return in;
}
Enter fullscreen mode Exit fullscreen mode

50. What Is istream?

istream means:

Input Stream

cin is an input stream.

Therefore:

istream &in
Enter fullscreen mode Exit fullscreen mode

means:

in is a reference to an input stream.


51. Why Is Time &t Used for Input?

Notice:

Time &t
Enter fullscreen mode Exit fullscreen mode

not:

const Time &t
Enter fullscreen mode Exit fullscreen mode

Why?

Because input needs to modify the object.

Suppose:

cin >> t1;
Enter fullscreen mode Exit fullscreen mode

The user enters:

2
90
Enter fullscreen mode Exit fullscreen mode

The function needs to store these values inside t1.

Therefore:

cin
 ↓
input values
 ↓
modify Time object
Enter fullscreen mode Exit fullscreen mode

So the Time object cannot be const.


52. Why Does Input Normalize the Time?

Suppose the user enters:

hours   = 2
minutes = 90
Enter fullscreen mode Exit fullscreen mode

The code:

t.hours = t.hours + t.minutes / 60;
t.minutes = t.minutes % 60;
Enter fullscreen mode Exit fullscreen mode

does:

90 / 60 = 1
Enter fullscreen mode Exit fullscreen mode

Therefore:

2 + 1 = 3 hours
Enter fullscreen mode Exit fullscreen mode

And:

90 % 60 = 30
Enter fullscreen mode Exit fullscreen mode

So:

2 hours 90 minutes
Enter fullscreen mode Exit fullscreen mode

becomes:

3 hours 30 minutes
Enter fullscreen mode Exit fullscreen mode

🔄 Part 14 — << vs >>

A very easy way to remember them:

Output

cout << t1;
Enter fullscreen mode Exit fullscreen mode

Think:

Time object
     ↓
   goes OUT
     ↓
   cout
Enter fullscreen mode Exit fullscreen mode

Therefore:

<< → OUTPUT


Input

cin >> t1;
Enter fullscreen mode Exit fullscreen mode

Think:

cin
 ↓
data goes INTO
 ↓
Time object
Enter fullscreen mode Exit fullscreen mode

Therefore:

>> → INPUT


🗺️ Part 15 — Complete Operator Map

Now let's put everything together.

                    OPERATOR OVERLOADING
                            |
          ┌─────────────────┼─────────────────┐
          ↓                 ↓                 ↓
       BINARY             UNARY             STREAM
          |                 |                 |
      +   -   =           ++   --           <<   >>
          |                 |                 |
     2 operands          1 operand       input/output
Enter fullscreen mode Exit fullscreen mode

📋 Quick Reference Table

Operator Example Type Function
+ t1 + t2 Binary operator+()
- t1 - t2 Binary operator-()
= t1 = t2 Binary operator=()
++ ++t1 Unary operator++()
++ t1++ Unary operator++(int)
-- --t1 Unary operator--()
-- t1-- Unary operator--(int)
<< cout << t1 Stream operator<<()
>> cin >> t1 Stream operator>>()

⭐ Part 16 — The Most Important Mental Model

If you remember only one thing from this entire article, remember this.

When you see:

t1 + t2;
Enter fullscreen mode Exit fullscreen mode

think:

t1.operator+(t2);
Enter fullscreen mode Exit fullscreen mode

When you see:

t1 - t2;
Enter fullscreen mode Exit fullscreen mode

think:

t1.operator-(t2);
Enter fullscreen mode Exit fullscreen mode

When you see:

t1 = t2;
Enter fullscreen mode Exit fullscreen mode

think:

t1.operator=(t2);
Enter fullscreen mode Exit fullscreen mode

When you see:

++t1;
Enter fullscreen mode Exit fullscreen mode

think:

t1.operator++();
Enter fullscreen mode Exit fullscreen mode

When you see:

t1++;
Enter fullscreen mode Exit fullscreen mode

think:

t1.operator++(int);
Enter fullscreen mode Exit fullscreen mode

For output:

cout << t1;
Enter fullscreen mode Exit fullscreen mode

conceptually:

operator<<(cout, t1);
Enter fullscreen mode Exit fullscreen mode

For input:

cin >> t1;
Enter fullscreen mode Exit fullscreen mode

conceptually:

operator>>(cin, t1);
Enter fullscreen mode Exit fullscreen mode

🧠 One Big Picture

Think of Operator Overloading like this:

                    t1 + t2
                       |
                       ↓
              "What should + do
               for Time objects?"
                       |
                       ↓
                operator+()
                       |
                       ↓
                  calculate
                       |
                       ↓
                 return Time
Enter fullscreen mode Exit fullscreen mode

And for unary operators:

                    ++t1
                      |
                      ↓
                operator++()
                      |
                      ↓
                 change t1
                      |
                      ↓
                return result
Enter fullscreen mode Exit fullscreen mode

And for streams:

                 cout << t1
                      |
                      ↓
                 operator<<()
                      |
                      ↓
                read Time object
                      |
                      ↓
                   display
Enter fullscreen mode Exit fullscreen mode

❓ Part 17 — Common Beginner Questions

❓ Why can't I simply use t1 + t2?

Because C++ doesn't automatically know what + should mean for two objects of your custom Time class.

We define that behavior through Operator Overloading.


❓ Why is + binary?

Because:

t1 + t2
Enter fullscreen mode Exit fullscreen mode

contains two operands.


❓ Why is ++ unary?

Because:

++t1
Enter fullscreen mode Exit fullscreen mode

contains one operand.


❓ Why does postfix ++ have int?

Because C++ needs a way to distinguish:

operator++()
Enter fullscreen mode Exit fullscreen mode

from:

operator++(int)
Enter fullscreen mode Exit fullscreen mode

The first represents prefix.

The second represents postfix.


❓ What is this?

this is a pointer to the current object.


❓ What is *this?

*this represents the actual current object.


❓ Why is const used?

When we don't want a function to modify an object through a parameter.

For example:

const Time &t
Enter fullscreen mode Exit fullscreen mode

means:

We can read the object, but we cannot modify it through t.


❓ Why is & used?

It creates a reference.

A reference allows us to work with an existing object instead of creating another separate object.


❓ Why do we need temp?

For + and -, temp is used to build and store the result.

For postfix ++ and --, temp is used to save the old value before changing the original object.


❓ Why is output const?

Because output only needs to read the object.


❓ Why isn't input const?

Because input needs to change the object and store the entered values inside it.


🧪 Part 18 — Practice Questions

Before looking at the answers, try these yourself.

Question 1

Is this unary or binary?

t1 + t2;
Enter fullscreen mode Exit fullscreen mode

Question 2

Is this unary or binary?

++t1;
Enter fullscreen mode Exit fullscreen mode

Question 3

Which function handles this?

t1 + t2;
Enter fullscreen mode Exit fullscreen mode

Question 4

Which function handles this?

t1++;
Enter fullscreen mode Exit fullscreen mode

Question 5

Why does postfix ++ have int?

Question 6

What does this represent?

Question 7

What does *this represent?

Question 8

Why do we use % 60?

Question 9

Which operator handles:

cout << t1;
Enter fullscreen mode Exit fullscreen mode

Question 10

Which operator handles:

cin >> t1;
Enter fullscreen mode Exit fullscreen mode

✅ Answers

1. Binary

t1 + t2;
Enter fullscreen mode Exit fullscreen mode

has two operands.

Therefore:

Binary
Enter fullscreen mode Exit fullscreen mode

2. Unary

++t1;
Enter fullscreen mode Exit fullscreen mode

has one operand.

Therefore:

Unary
Enter fullscreen mode Exit fullscreen mode

3.

operator+()
Enter fullscreen mode Exit fullscreen mode

4.

operator++(int)
Enter fullscreen mode Exit fullscreen mode

5.

The int is a dummy parameter used to distinguish postfix ++ from prefix ++.


6.

this is a pointer to the current object.


7.

*this represents the actual current object.


8.

To keep minutes within the normal range of:

0–59
Enter fullscreen mode Exit fullscreen mode

For example:

70 % 60 = 10
Enter fullscreen mode Exit fullscreen mode

9.

operator<<()
Enter fullscreen mode Exit fullscreen mode

10.

operator>>()
Enter fullscreen mode Exit fullscreen mode

📝 Part 19 — Final Cheat Sheet

╔══════════════════════════════════════════════╗
║          C++ OPERATOR OVERLOADING            ║
╚══════════════════════════════════════════════╝

BINARY
──────────────────────────────────────────────
t1 + t2  → operator+()
t1 - t2  → operator-()
t1 = t2  → operator=()

UNARY
──────────────────────────────────────────────
++t1     → operator++()
t1++     → operator++(int)

--t1     → operator--()
t1--     → operator--(int)

STREAM
──────────────────────────────────────────────
cout << t1 → operator<<()
cin >> t1  → operator>>()

IMPORTANT
──────────────────────────────────────────────
2 operands → Binary
1 operand  → Unary

++t → Prefix  → change first
t++ → Postfix → save old value first

--t → Prefix  → change first
t-- → Postfix → save old value first

<< → Output
>> → Input

this  → pointer to current object
*this → actual current object

const → don't modify through this reference
&     → reference
Enter fullscreen mode Exit fullscreen mode

🎯 Final Takeaway

Operator Overloading can look complicated when we first see:

Time Time::operator+(const Time &t)
Enter fullscreen mode Exit fullscreen mode

But if we break it down:

Time
 ↓
return type

Time::
 ↓
belongs to Time class

operator+
 ↓
defines +

const
 ↓
don't modify the parameter

Time
 ↓
parameter type

&
 ↓
reference

t
 ↓
parameter name
Enter fullscreen mode Exit fullscreen mode

Suddenly the declaration isn't so mysterious.

Then look at the body:

create result object
        ↓
add hours
        ↓
add minutes
        ↓
convert extra minutes
        ↓
return result
Enter fullscreen mode Exit fullscreen mode

And the complete flow becomes:

t1 + t2
   ↓
t1.operator+(t2)
   ↓
operator+()
   ↓
calculate
   ↓
return Time object
Enter fullscreen mode Exit fullscreen mode

That's the real idea behind Operator Overloading.

Don't memorize the syntax. Understand the relationship between the operator, the object, the function, and the result.

Once that mental model becomes clear, Operator Overloading stops looking like a collection of strange symbols and starts becoming a normal C++ concept.


📂 Complete Notes & Practice Material

If you want to go beyond this article, I've also organized the complete learning material in my GitHub repository.

It includes:

  • 📖 Detailed beginner-friendly notes
  • 🎨 Visual study notes
  • 💻 Complete C++ code
  • 🔍 Step-by-step concept explanations
  • 🧪 Practice questions with answers
  • 📌 Quick-reference / cheat sheets

👉 Explore the complete repository:
https://github.com/Poushmita/cpp_doubtClearance

You can use the repository alongside this article to read the concepts, explore the code, revise visually, and practice them yourself.


💭 Why I Like Learning This Way

This guide started with a simple situation: a friend asked me for help understanding Operator Overloading.

While explaining it, I realized that sometimes a concept feels difficult not because the concept itself is extremely complicated, but because too many small things are assumed to be already understood.

A beginner may understand Time but not Time&.

They may understand ++ but not why:

operator++(int)
Enter fullscreen mode Exit fullscreen mode

contains int.

They may understand cout but not why:

ostream& operator<<(ostream &out, const Time &t)
Enter fullscreen mode Exit fullscreen mode

looks different from:

Time Time::operator+(const Time &t)
Enter fullscreen mode Exit fullscreen mode

So I decided to write these notes with one simple rule:

Don't just explain what the code does. Explain why the code is written that way.

If you're learning C++ and Operator Overloading has ever felt confusing, I hope this guide helps you understand it one small piece at a time.

And if you're helping someone else learn it, feel free to use these notes as a teaching resource. ❤️

If you find something that could be explained more clearly, feel free to suggest an improvement.

Top comments (0)