Operator Overloading Examples in C++

Almost all the operators can be overloaded in infinite different ways. Following are some examples to learn more about operator overloading. All the examples are closely connected.


Overloading Arithmetic Operator in C++

Arithmetic operator are most commonly used operator in C++. Almost all arithmetic operator can be overloaded to perform arithmetic operation on user-defined data type. In the below example we have overridden the + operator, to add to Time(hh:mm:ss) objects.


Example: overloading + Operator to add two Time class object

#include <iostream.h>
#include <conio.h>
class Time
{
    int h,m,s;
    public:
    Time()
    {
        h=0, m=0; s=0;
    }
    void setTime();
    void show()
    {
        cout<< h<< ":"<< m<< ":"<< s;
    }
    
    //overloading '+' operator
    Time operator+(time);   
};

Time Time::operator+(Time t1)	//operator function
{
    Time t;
    int a,b;
    a = s+t1.s;
    t.s = a%60;
    b = (a/60)+m+t1.m;
    t.m = b%60;
    t.h = (b/60)+h+t1.h;
    t.h = t.h%12;
    return t;
}

void time::setTime()
{
    cout << "\n Enter the hour(0-11) ";
    cin >> h;
    cout << "\n Enter the minute(0-59) ";
    cin >> m;
    cout << "\n Enter the second(0-59) ";
    cin >> s;
}

void main()
{
    Time t1,t2,t3;
 
    cout << "\n Enter the first time ";
    t1.setTime();
    cout << "\n Enter the second time ";
    t2.setTime();
    t3 = t1 + t2;	//adding of two time object using '+' operator
    cout << "\n First time ";
    t1.show();
    cout << "\n Second time ";
    t2.show();
    cout << "\n Sum of times ";
    t3.show();
    getch();
}

While normal addition of two numbers return the sumation result. In the case above we have overloaded the + operator, to perform addition of two Time class objects. We add the seconds, minutes and hour values separately to return the new value of time.

In the setTime() funtion we are separately asking the user to enter the values for hour, minute and second, and then we are setting those values to the Time class object.

For inputs, t1 as 01:20:30(1 hour, 20 minute, 30 seconds) and t2 as 02:15:25(2 hour, 15 minute, 25 seconds), the output for the above program will be:

1:20:30 2:15:25 3:35:55

First two are values of t1 and t2 and the third is the result of their addition.


Overloading I/O operator in C++

The first question before learning how to override the I/O operator should be, why we need to override the I/O operators. Following are a few cases, where overloading the I/O operator proves useful:

  • We can overload output operator << to print values for user defined datatypes.
  • We can overload output operator >> to input values for user defined datatypes.

In case of input/output operator overloading, left operand will be of types ostream& and istream&

Also, when overloading these operators, we must make sure that the functions must be a Non-Member function because left operand is not an object of the class.

And it must be a friend function to access private data members.

You have seen above that << operator is overloaded with ostream class object cout to print primitive datatype values to the screen, which is the default behavious of << operator, when used with cout. In other words, it is already overloaded by default.

Similarly we can overload << operator in our class to print user-defined datatypes to screen. For example we can overload << in our Time class to display the value of Time object using cout rather than writing a custom member function like show() to print the value of Time class objects.

Time t1(3,15,48);
// like this, directly
cout << t1;

In the next section we will learn how to do that.

NOTE: When the operator does not modify its operands, the best way to overload the operator is via friend function.


Example: overloading << Operator to print Class Object

We will now overload the << operator in the Time class,

#include<iostream.h>
#include<conio.h>
class Time
{
    int hr, min, sec;
    public:
    // default constructor
    Time()
    {
        hr=0, min=0; sec=0;
    }
    
    // overloaded constructor
    Time(int h, int m, int s)
    {
        hr=h, min=m; sec=s;
    }
    
    // overloading '<<' operator
    friend ostream& operator << (ostream &out, Time &tm); 
};

// define the overloaded function
ostream& operator << (ostream &out, Time &tm)
{
    out << "Time is: " << tm.hr << " hour : " << tm.min << " min : " << tm.sec << " sec";
    return out;
}

void main()
{
    Time tm(3,15,45);
    cout << tm;
}

Time is: 3 hour : 15 min : 45 sec

This is simplied in languages like Core Java, where all you need to do in a class is override the toString() method of the String class, and you can define how to print the object of that class.


Overloading Relational Operator in C++

You can also overload relational operators like == , != , >= , <= etc. to compare two object of any class.

Let's take a quick example by overloading the == operator in the Time class to directly compare two objects of Time class.

class Time
{
    int hr, min, sec;
    public:
    // default constructor
    Time()
    {
        hr=0, min=0; sec=0;
    }
    
    // overloaded constructor
    Time(int h, int m, int s)
    {
        hr=h, min=m; sec=s;
    }
    
    //overloading '==' operator
    friend bool operator==(Time &t1, Time &t2);
};

/* 
    Defining the overloading operator function
    Here we are simply comparing the hour, minute and
    second values of two different Time objects to compare
    their values
*/
bool operator== (Time &t1, Time &t2)
{
    return ( t1.hr == t2.hr && t1.min == t2.min && t1.sec == t2.sec );
}

void main()
{
    Time t1(3,15,45);
    Time t2(4,15,45);
    if(t1 == t2)
    {
        cout << "Both the time values are equal";
    }   
    else 
    {
        cout << "Both the time values are not equal";
    }
}

Both the time values are not equal

As the hour value of object t1 is 3 and for object t2 it is 4, hence they are not equal.


Copy Constructor vs. Assignment Operator (=)

Assignment operator is used to copy the values from one object to another already existing object. For example:

Time tm(3,15,45); // tm object created and initialized
Time t1;    // t1 object created
t1 = tm;    // initializing t1 using tm

Whereas, Copy constructor is a special constructor that initializes a new object from an existing object.

Time tm(3,15,45); // tm object created and initialized
Time t1(tm);    //t1 object created and initialized using tm object

In case of Copy constructor, we provide the object to be copied as an argument to the constructor. Also, we first need to define a copy constructor in our class. We have covered Copey constructor in detail here: Copy Constructor in C++