Operator Overloading in C++

C++ supports polymorphism which means that you can define different functions and operators for different types and in different classes. There must be some differences in the parameters. The number of parameters must be different, types must be different. This is called overloading. If one class extends another class and they both define the same operator or function then this is called overriding.

In this post we shall overload the +.- and * operators for a Currency class. The Currency class is used for manipulating currencies. Currency has rupees and paise and both of these will always be integers. A rupee is made of 100 paise.

Here is a simple program for the same


#include <iostream>

using namespace std;
class Currency
{
int paise;
public:Currency()
{
this->paise=0;
}
public:Currency(int paise)
{
this->paise=paise;
}
public:Currency(int rupees,int paise)
{
this->paise=100*rupees+paise;
}
public:void print()
{
int r=paise/100;
int p=paise%100;
cout<<"Rs "<<r<<"."<<p<<"\n";
}
public: Currency operator + (Currency c)
{
Currency temp(paise+c.paise);
return temp;
}
};
int main()
{
Currency c1(10,250);
c1.print();
c1=c1+c1;
c1.print();
return 0;
}

Try and implement a – operator.

 

Another example where we implement an Angle class.


#include <iostream>

using namespace std;
class Angle
{
private: int angle;
public:Angle()
{
this->angle=0;
}
public:Angle(int angle)
{
angle=angle % 360;
angle=angle+360;
angle=angle%360;
this->angle=angle;
}

public:void print()
{
cout<<"Angle "<<angle<<"\n";
}
friend Angle operator + (Angle a1,Angle a2);
};
Angle operator + (Angle a1,Angle a2)
{
Angle temp(a1.angle+a2.angle);
return temp;
}

&nbsp;

int main()
{
Angle a1(-250);
a1.print();
a1=a1+a1;
a1.print();
a1=a1+a1;
a1.print();
return 0;
}

Now, we will subtract and multiply.

Angle.cpp


#include <iostream>

using namespace std;
class Angle
{
private: int angle;
public:Angle()
{
this->angle=0;
}
public:Angle(int angle)
{
angle=angle % 360;
angle=angle+360;
angle=angle%360;
this->angle=angle;
}

public:void print()
{
cout<<"Angle "<<angle<<"\n";
}
friend Angle operator + (Angle a1,Angle a2);
friend Angle operator - (Angle a1,Angle a2);
friend Angle operator * (Angle a1,Angle a2);
};
Angle operator + (Angle a1,Angle a2)
{
Angle temp(a1.angle+a2.angle);
return temp;
}

Angle operator - (Angle a1,Angle a2)
{
Angle temp(a1.angle-a2.angle);
return temp;
}
Angle operator * (Angle a1,Angle a2)
{
Angle temp(a1.angle*a2.angle);
return temp;
}
int main()
{

Angle a1(150);
Angle a2(100);
a1.print();
a2.print();
Angle difference =a1-a2;
difference.print();
difference=a2-a1;
difference.print();
Angle product=a1*a2;
product.print();
return 0;
}

 

Leave a Reply