blog

Home / DeveloperSection / Blogs / Operator Overloading in C++

Operator Overloading in C++

priyanka kushwaha2167 05-Feb-2015

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>
usingnamespace std;
usingnamespace System;
class  Operatoion
{
            double firstNumber,SecNumber;
public:
            void getVal(doublefn,doublesn)
            {
                        firstNumber=fn;
                        SecNumber=sn;
            }
            void distplay()
            {
                        cout<<"\n First Number is ";cout<<firstNumber;
                        cout<<"\n Second Number is";cout<<SecNumber;
            }
            Operatoion operator +(Operatoionnumber)
            {
                        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;
}
 

Updated 05-Feb-2015

Leave Comment

Comments

Liked By