Operator Overloading in C++: Operator overloading is one of the features that come with c++ programming language as a part of object-oriented polymorphism.

In operator overloading, the operators like +, -, ++, –, /, * etc can be overloaded so that they can be used not only with primitives data types but also with user-defined types.

What do I mean by that?

Suppose you have two integer variables:

We can do almost all arithmetic operations on these two integers using differnt operators. For e.g to add these two integers we use + opearator as

If we do the same operation on objects(user defined), will it work like previous? For e.g

Definetly, it will cause error because normally we cannot add two objects, but with operator overloading we can make this possible.
Now you have basic idea, why opearator overloading is used? So lets start learning Opearator overloading from its two types.

Types of Operator Overloading

Binary Operator Overloading

Binary Operator is that operator which requires/operates on two variables/operands. eg +, – etc.

In this operator overloading example, we are creating two objects of a Mystring class. Each Mystring objects has string str variable which stores a string.

We are overloading + operator for using it to concatenate the two strings of two different objects of the same class.

Unary Operator Overloading

A unary operator is that operator which operates only on single variable/operand. eg ++,– etc.

In the same operator overloading example, we are overloading — operator to use it for converting a string to lower case.

Operator Overloading Example

Output

operator overloading example

In this example, we have shown overloading of operators in c++ as a member function. It means that the overloaded operator can work only on the objects of the class which it is the member function of. Normal use of + operator on Integer data type will give normal addition as output.

That’s all for the operator overloading in c++. If you have any doubts then comment below.

Leave a Reply

Close Menu