on Leave a Comment

C++ Operator Overloading

C++ allows operator overloading. Overloaded operators can do operations on predefined data type elements. Overloading allow us to implement polymorphism in C++. Operator overloading means more than one definition of an operator.

There are many operators in C++ like +, -, *, / and so on. But these operators works on built-in data type variable. For example, 
int a=1,b=2,c;
c=a+b;                   //It will works

But these operators do not works on user-defined data types. For example,
object3=object1+object2;         //It will not work

Any operator that works on built-in data types can be overloaded.


Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Increment and Decrement Operators

C++ operator overloading syntax:

return type classname :: operator operatorsymbol (list of arguments)
{
        //Function Body
}

How to implement operator overloading?

In c++, operator overloading can be done for class objects. You can implement operator overloading by
1.     Member Function
2.     Non-Member Function
3.     Friend Function

To overload an operator, operator keyword is used.

For example:

class classname
{
        ...
        public:
          returntype operator operatorsymbol (list of arguments)
         {
                //Function Body
         }
        ...
};

C++ operator overloading example:

C++ program to overload + operator

#include<iostream>
using namespace std;
class addobject
{
    int a,b;
public:
    addobject operator + (addobject obj)
    {
        addobject t;
        t.a=a+obj.a;
        t.b=b+obj.b;
        return t;
    }
    void getdata(int x,int y)
    {
        a=x;
        b=y;
    }
    void putdata()
    {
        cout<<"a = "<<a<<endl<<"b = "<<b;
    }
};
int main()
{
    addobject obj1,obj2,obj3;
    obj1.getdata(1,2);
    obj2.getdata(3,4);
    obj3=obj1+obj2;
    obj3.putdata();
    return 0;
}

OUTPUT:

a = 4
b = 6

In this program, you can also also write this statement obj3=obj1+obj2 as obj3=obj1.operator+(obj2).



0 comments:

Post a Comment