C++ Program For Binary Operator Overloading for Arithmetic Operator

Free C++ course with real-time projects Start Now!!

Program 1

//Binary Operator overloading (Arithmetic operator)
#include<iostream>
#define clrscr() system("cls")
using namespace std;
class Test
{
    int n;
    public:
    Test(int n)
    {
        this->n=n;
    }
    Test(){}

    void display();
   Test operator+(Test &k);
   Test operator-(Test &k);
   Test operator*(Test &k);
   Test operator/(Test &k);
   Test operator%(Test &k);
};
Test Test::operator+(Test &k)
{
      Test temp;
      temp.n=n+k.n;
      return temp;
}
Test Test::operator-(Test &k)
{
      Test temp;
      temp.n=n-k.n;
      return temp;
}
Test Test::operator*(Test &k)
{
      Test temp;
      temp.n=n*k.n;
      return temp;
}
Test Test::operator/(Test &k)
{
      Test temp;
      temp.n=n/k.n;
      return temp;
}
Test Test::operator%(Test &k)
{
      Test temp;
      temp.n=n%k.n;
      return temp;
}


void Test::display()
{
    cout<<"\n "<<n;
}
int main()
{
      clrscr();
      int x,y;
      cout<<"Enter two numbers: ";
      cin>>x>>y;
     Test T1(x);
     Test T2(y);
     Test T3;
     cout<<"\n Object Arithmetic operations: ";
     cout<<"\nAddition";
     T3=T1+T2;  
     T3.display();
     cout<<"\nSubtraction";
     T3=T1-T2;  
     T3.display();
     cout<<"\nMultiplication";
     T3=T1*T2;  
     T3.display();
     cout<<"\ndivision";
     T3=T1/T2;  
     T3.display();
     cout<<"\nMod";
     T3=T1%T2;  
     T3.display();
     return 0;
}
// T1+T2    T1.operator+(T2)
// T1-T2    T1.operator-(T2)
// T1*T2    T1.operator*(T2)
// T1/T2    T1.operator/(T2)

 

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *