Overloading Binary Operators ( +, -, *, /, % )
Example:1
C++ program to overload binary operator “+”. (Add two objects using overloaded operator “+”.)
// to overload + operator // add two objects #include<iostream> #include<conio.h> using namespace std; class sample { private: int a; public: sample(); sample(int n); void get(); void disp(); sample operator+(sample s); }; sample::sample() { a=0; } sample::sample(int n) { a=n; } void sample::get() { cout<<"Enter the value of a "; cin>>a; } void sample::disp() { cout<<"a= "<<a<<endl; } sample sample::operator+(sample s) { sample t; t.a=a+s.a; return(t); } int main() { sample s1,s2,s3; s1.get();s2.get(); s1.disp();s2.disp(); s3=s1+s2;//s3=s1.operator+(S2); s3.disp(); getch(); return(0); }
Output:
Enter the value of a 10
Enter the value of a 20
a= 10
a= 20
a= 30
Example:2
C++ program to overload binary operator “-“.
// to overload - operator // add two objects #include<iostream> #include<conio.h> using namespace std; class sample { private: int a; public: sample(); sample(int n); void get(); void disp(); sample operator-(sample s); }; sample::sample() { a=0; } sample::sample(int n) { a=n; } void sample::get() { cout<<"Enter the value of a "; cin>>a; } void sample::disp() { cout<<"a= "<<a<<endl; } sample sample::operator-(sample s) { sample t; t.a=a-s.a; return(t); } int main() { sample s1,s2,s3; s1.get();s2.get(); s1.disp();s2.disp(); s3=s1-s2;//s3=s1.operator-(S2); s3.disp(); getch(); return(0); }
Output:
Enter the value of a 10
Enter the value of a 20
a= 10
a= 20
a= -10
Example:3
C++ program to overload binary operator “*”.
// to overload * operator // with two objects #include<iostream> #include<conio.h> using namespace std; class sample { private: int a; public: sample(); sample(int n); void get(); void disp(); sample operator*(sample s); }; sample::sample() { a=0; } sample::sample(int n) { a=n; } void sample::get() { cout<<"Enter the value of a "; cin>>a; } void sample::disp() { cout<<"a= "<<a<<endl; } sample sample::operator*(sample s) { sample t; t.a=a*s.a; return(t); } int main() { sample s1,s2,s3; s1.get();s2.get(); s1.disp();s2.disp(); s3=s1*s2;//s3=s1.operator*(S2); s3.disp(); getch(); return(0); }
Output:
Enter the value of a 10
Enter the value of a 20
a= 10
a= 20
a= 200