Programming

C++ Program to Implement Binary Operator Overloading

Write a menu driven program to implement the various binary operators using the concept of binary operator overloading.

Source Code

#include<conio.h>
#include<iostream>
#include<process.h>
using namespace std;
class Test
{
private: int val;
public: Test()
{val=0;}
Test(int a)
{val=a;}
void getval()
{cout<<endl<<val<<endl;}
Test operator +(Test t2)
{
Test t;
t.val=val+t2.val;
return t;
}
Test operator -(Test t2)
{
Test t;
t.val=val-t2.val;
return t;
}
Test operator *(Test t2)
{
Test t;
t.val=val*t2.val;
return t;
}
Test operator /(Test t2)
{
Test t;
t.val=val/t2.val;
return t;
}
};
int main()
{
int c;
Test t1(10),t2(5),t3;
cout<<“The initial data are 10 and 5″<<endl;
do{
cout<<endl<<“Menu”<<endl<<“1. +”<<endl<<“2. -“<<endl<<“3. *”
<<endl<<“4. /”<<endl<<“5. exit”<<endl<<“Enter yout choice: “;
cin>>c;
switch(c)
{
case 1:t3=t1+t2;
t3.getval();
break;
case 2: t3=t1-t2;
t3.getval();
break;
case 3: t3=t1*t2;
 t3.getval(); break;
case 4: t3=t1/t2; t3.getval();
 break;
case 5: exit(1);
+break;
default:cout<<endl<<“Invalid Choice!!!”;
}
}while(c!=5);
getch();
}

Output

Binary Operator Overloading

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.