C++ Program For Arithmetic Operator Overloading for Object and Primitive

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

//Binary Operator overloading 
//(Arithmetic operator for object and primitive)
#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+(int x);
      Test operator-(int x);
      Test operator*(int x);
      Test operator/(int x);
      Test operator%(int x);
};
void Test::display()
{
    cout<<n;
}
Test Test::operator+(int x)
{
        Test temp;
        temp.n=n+x;
        return temp;       
}
Test Test::operator-(int x)
{
        Test temp;
        temp.n=n-x;
        return temp;       
}
Test Test::operator*(int x)
{
        Test temp;
        temp.n=n-x;
        return temp;       
}
Test Test::operator/(int x)
{
        Test temp;
        temp.n=n/x;
        return temp;       
}
Test Test::operator%(int x)
{
        Test temp;
        temp.n=n%x;
        return temp;       
}
int main()
{
      clrscr();
      Test T1(100);
      Test T2;
      cout<<"\nAddition ";
      T2=T1+50;  // T2=T1.operator+(50)
       T2.display();

      cout<<"\nSubtraction ";
      T2=T1-50;  // T2=T1.operator-(50)
      T2.display();
      cout<<"\nMultiplication ";
      T2=T1*50;  // T2=T1.operator*(50)
      T2.display();

       cout<<"\nDivision ";
      T2=T1/50;  // T2=T1.operator/(50)
      T2.display();
       cout<<"\nMod";
      T2=T1%50;  // T2=T1.operator%(50)
      T2.display();
      return 0;
}

 

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

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