Binary Operator Overloading in C++
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
// Operator overloading
#include<iostream>
using namespace std;
class TestAdd
{
int n;
public:
TestAdd(int n)
{
this->n=n;
}
TestAdd()
{
n=0;
}
void display();
TestAdd operator+(TestAdd K);
TestAdd operator-(TestAdd K);
};
void TestAdd::display()
{
cout<<n<<endl;
}
TestAdd TestAdd::operator+(TestAdd K)
{
TestAdd temp;
temp.n=n+K.n;
return temp;
}
TestAdd TestAdd::operator-(TestAdd K)
{
TestAdd temp;
temp.n=n-K.n;
return temp;
}
int main()
{
system("cls");
TestAdd T1(50);
TestAdd T2(30);
TestAdd T3;
T1.display();
T2.display();
T3.display();
T3=T1+T2; // T3=T1.operator+(T2)
cout<<"\nAddition is :";
T3.display();
T3=T1-T2; // T3=T1.operator-(T2)
cout<<"\nSubtraction is :";
T3.display();
return 0;
}Program 2
// Operator overloading
#include<iostream>
using namespace std;
class TestAdd
{
int n;
public:
TestAdd(int n)
{
this->n=n;
}
TestAdd()
{
n=0;
}
TestAdd operator+(int m);
TestAdd operator-(int m);
void display();
};
TestAdd TestAdd::operator+(int m) //m=20
{
TestAdd temp;
temp.n=n+m;
return temp;
}
TestAdd TestAdd::operator-(int m) //m=20
{
TestAdd temp;
temp.n=n-m;
return temp;
}
void TestAdd::display()
{
cout<<endl<<n<<endl;
}
int main()
{
system("cls");
TestAdd T1(50);
TestAdd T2;
T2=T1+20; // T2=T1.operator+(20)
T2.display();
T2=T1-20; // T2=T1.operator-(20)
T2.display();
return 0;
} Your opinion matters
Please write your valuable feedback about DataFlair on Google

