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
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;

RELATED PAGES
- Objects and Classes
- Operator Overloading
- Classes and Objects-II


Basic Financial Terms
Basic Financial terms in Corporate and Mathematical Finance
Financial Portfolio Analysis
Selection of assets, risk and return, and portfolio analysis
Financial Mathematics Notes
View the online notes for Financial Mathematics (CT1)
Financial Computing with C++
Learn Financial Computing with C++ step by step