Operator Overloading

C++BasicsInputArithmeticConditionsLoops → Array → Functions → Random Numbers → Classes and Objects → Operator Overloading

The operator overloading means giving the normal C++ operators, such as +, -, *, /, >, < normal meaning. Or more simple, we can use these operators for our private variables in the class.

Operator Overloading: Construction

class operator(class object)
{
class newObject;
return newObject;
}

We are using our previous example to show how operator overloading works. Consider the class where we ourselves set the two radius, and will ask the user to input the third variable. Then, we use operator overloading + to add the three variables.

#include <iostream>
using namespace std;
class Circle
{
private:
float radius;
public:
void setRadius(float rad)
{
radius = rad;
}
void getRadius()
{
cout << "Enter Radius: "; cin >> radius;
}
void showRadius()
{
cout << "Radius = " << radius << endl;
}
Circle operator+(Circle ob) //add the variables
{
Circle newob; //new object
newob.radius = radius + ob.radius;
return newob;
}
};
int main()
{
Circle c1, c2, c3, c4; //four objects
c1.setRadius(3.2);
c2.setRadius(4.5);
c3.getRadius();
c1.showRadius();
c2.showRadius();
c3.showRadius();
c4 = c1 + c2 + c3;
c4.showRadius();
return 0;
}

Similarly, to multiply the private variable radius change + by * in the above example. For example,
change Circle operator+(Circle ob) by Circle operator*(Circle ob)
change newob.radius = radius + ob.radius; by newob.radius = radius * ob.radius;
And,
change c4 = c1 + c2 + c3; by c4 = c1 * c2 * c3;

NEXT: More on Classes and Objects