In this blog, I’m explaining about Operator Overloading in C++

 
What is operator overloading?

1.   Changing the definition of an operator so it can be applied on the objects of a class is called operator overloading.

2.  To overload an operator, we need   to write a function for the operator we are overloading.

3.   Overloading  is allowed only if at least one operand is a class  instrance (e.g you cannot overload an operator to take two integers as operand.)

Example:
// OperatorOverloading.cpp : main project file.
 
#include "stdafx.h"
#include<iostream>
using namespace std;
using namespace System;
class  Operatoion
{
            double firstNumber,SecNumber;
public:
            void getVal(double fn,double sn)
            {
                        firstNumber=fn;
                        SecNumber=sn;
            }
            void distplay()
            {
                        cout<<"\n First Number is ";cout<<firstNumber;
                        cout<<"\n Second Number is";cout<<SecNumber;
            }
            Operatoion operator +(Operatoion number)
            {
                        Operatoion objOper;
                        objOper.firstNumber=firstNumber+number.firstNumber;
                        objOper.SecNumber=SecNumber+number.SecNumber;
                        return objOper;
            }
            void operator ++()
            {
                        firstNumber++;
                        SecNumber++;
            }
public:
             Operatoion
();
            ~ Operatoion
();
 
private:
 
};
 
 Operatoion
:: Operatoion
()
{
}
 
 Operatoion
::~ Operatoion
()
{
}
 
int main(array<System::String ^> ^args)
{
            Operatoion objFirst,objSecond,objResult;
            objFirst.getVal(10,20);
            objSecond.getVal(30,40);
            objResult=objFirst+objResult;
            objResult=objFirst+objSecond;
            objResult.distplay();
            objResult++;
            objResult.distplay();
            objFirst++;
            objFirst.distplay();
            Console::ReadKey(0);
    return 0;
}
 

Leave Comment