In this article we will discuss what is operator overloading in C++, why do we need it and how to overload an operator for a user defined class.

What is Operator overloading ?

Operator Overloading means providing multiple definition for the same operator.

For example, using + operator with two integers will add the numbers, whereas, using + operator with two std::string arguments will concatenate the strings i.e.

Output:

Operators for primitive data types like int, double and string etc. are already overloading. But for user defined classes, we need to overload them.

Need of Overloading Operator for a User Defined Class ?

C++ provides the facility to overload operator for user defined classes too.

Suppose we have a user defined class ComplexNumber and we created 2 objects of it i.e.

Now suppose we want to use + operator with its two objects i.e.

It will show compile error i.e. because like other operators, + operator is by default  overloaded for primitive data types only but not for user defined classes.

Compiler don’t know what to do when we call + operator with operands of type ComplexNumber.

If we want to use + operator with a user defined class then we need to overload it . Let’s see how to overload + operator in class ComplexNumber

How to overload operator in use defined class ?

To overload an operator for user defined class, we will write a separate operator function for it i.e.

Here X represents the operator symbol i.e. +, – , / etc.

These operator functions can be: either global function or class member function

Overload + operator as global function for User Defined Class ComplexNumber

As + operator is a binary operator, so it will take two arguments i.e.

It accepts two arguments i.e. two objects of our user defined class and returns a new object of same class.

Now as this function is accessing private members of user defined class ComplexNumber. So, we need to declare it as friend function i.e.

Now, when we will use + operator with ComplexNumber class objects, then it will call this global overloaded function i.e.

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.