c++

C++ Operator Overloading

In C++,it's possible to change the way operator works (for user defined types).In this article, you will learn to implement operator overloading feature.

The meaning of an operator is always same for variable of basic types like: int, float, double etc. For example: To add two integers, + operator is used.

However, for user-defined types (like:objects), you can redefine the way operator works. For example:

If there are two objectsof a class that contains string as its data members. You can redefine the meaning of + operator and use it to concatenate those strings.

This feature in C++ programming that allows programmer to redefine the meaning of an operator (when they operate on class objects)is known as operator overloading.


Why is operator overloading used?

Operator overloading allows you to redefine the way operator works for user-defined types only(objects,structures).It cannot be used for built-in types(int,float,char etc.).

You do not need to create an operator function. Operator overloading cannot change the precedence and associatively of operators.

For Example:

You can replace the code like:

calculation=add(multiply(a,b),divide(a,b));

to

calculation=(a*b)+(a/b);


How to overload operators in C++ programming?

To overload an operator,a special operator function is defined inside the class as:

class className
{
    ........
        public
         returnType operator symbol (arguments)
    {
........
    }
    ........
}; 

Here, returnType is the return type of the function.
The returnType of the function is followed by operator keyword.
Symbol is the operator symbol you want to overload. Like: +, <, -, ++
You can pass arguments to the operator function in similar way as functions.


Example:-Operator overloading in C++ Programming.

++ Programming
#include<iostream>
using namespace std;
class Test
{
    private:
        int count;
    public:
    Test(): count(5){}
    void operator ++()
{
count=count+1;
}
void Display() {cout<<"Count:"<< count;}
};
int main()
{
Test t;
//this calls "functionvoidoperator++()" function
++t;
t.Display();
return 0;
}