Operator Overloading Examples
Operator Overloading Examples
Example 1: Let us multiply two fractions using the overloading of the multiplication operator in
C++.
#include <iostream>
using namespace std;
class Frac {
private:
int a;
int b;
public:
Frac() : a(0), b(0) {}
void in() {
cout << "Enter the numerator : ";
cin >> a;
cout<< "Enter the denominator : ";
cin >> b;
}
Frac operator * (const Frac &obj) {
Frac temp;
temp.a = a * obj.a;
temp.b = b * obj.b;
return temp;
}
void out() {
cout<<"The fraction is "<< a<<"/"<<b<<endl;
}
};
int main() {
Frac F1, F2, result;
cout << "Enter the first fraction:\n";
F1.in();
cout << "Enter the second fraction:\n";
F2.in();
result = F1 * F2;
result.out();
system("PAUSE");
}
#include <iostream>
using namespace std;
class OverLoad {
private:
int a;
int b;
public:
OverLoad() : a(0), b(0) {}
void in() {
cout << "Enter the first number : ";
cin >> a;
cout<< "Enter the second number : ";
cin >> b;
}
void operator-- () {
a= --a;
b= --b;
}
void out() {
cout<<"The decremented elements of the object are: "<<endl<< a<<" and " <<b<<endl;
}
};
int main() {
OverLoad obj;
obj.in();
--obj;
obj.out();
system("PAUSE");
}
#include <iostream>
using namespace std;
class NotOp {
private:
int a;
bool b;
public:
NotOp() : a(0), b(true) {}
void in() {
cout << "Enter the first number : ";
cin >> a;
cout<< "Enter true or false : ";
cin >> b;
}
void operator ! () {
a= !a;
b= !b;
}
void out() {
cout<<"Output: "<<endl<< a<<endl<<b<<endl;
}
};
int main() {
NotOp obj;
!obj;
obj.out();
system("PAUSE");
return 0;
}
Example4: Let us try overloading the increment and decrement operators through a C++
program.
#include<iostream>
using namespace std;
class UnaryOverload
{
int hr, min;
public:
void in()
{
cout<<"\n Enter the time: \n";
cin>>hr;
cout<<endl;
cin>>min;
}
void operator++(int)
{
hr++;
min++;
}
void operator--(int)
{
hr--;
min--;
}
void out()
{
cout<<"\nTime is "<<hr<<"hr "<<min<<"min";
}
};
int main()
{
UnaryOverload ob;
ob.in();
ob++;
cout<<"\n\n After Incrementing : ";
ob.out();
ob--;
ob--;
cout<<"\n\n After Decrementing : ";
ob.out();
system("PAUSE");
}
#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
count1.display();
system("PAUSE");
}