C++ → Basics → Input → Arithmetic → Conditions → Loops → Array → Functions → Random Numbers → Classes and Objects → Operator Overloading → More on Classes and Objects
In the previous sections we have learned basics of classes & objects and operator overloading. Now, we are going to make a simple class to obtain the area of a circle. And then, we add the two radius to obtain the new radius and the corresponding area. For example,
Enter Radius: r1 Find Area with r1
Enter Radius: r2 Find Area with r2
And, then use operator overloading to obtain r3 = r1 + r2. And
Find Area with r3
#include <iostream>
using namespace std;
const float pi = 3.14159265;
class Circle
{
private:
float radius;
public:
void getRadius()
{
cout << "Enter Radius: "; cin >> radius;
}
float area() //calculate the area
{
return pi*radius*radius;
}
Circle operator+(Circle ob) //add the two radius
{
Circle newob;
newob.radius = radius + ob.radius;
return newob;
}
};
int main()
{
Circle c1, c2, c3;
c1.getRadius();
c2.getRadius();
c3 = c1 + c2;
cout << c1.area() << endl;
cout << c2.area() << endl;
cout << c3.area() << endl; //area with r3 = r1+r2
return 0;
}
Remember: Here Area-3 is NOT equal to Area-1 + Area-2. But, Area-3 is corresponds to r3 where r3 = r1 + r2.
In the next example, in addition to the above program, we use another operator greater than (>) to check which circle is larger. Remember, the circle has larger radius has larger area. So, in the last previous example we added the variable radius, now we also compare the two radius variables.
#include <iostream>
using namespace std;
const float pi = 3.14159265;
class Circle
{
private:
float radius;
public:
void getRadius()
{
cout << "Enter Radius: "; cin >> radius;
}
float myArea() //calculate the area
{
return pi*radius*radius;
}
float myRadius() //calculate the area
{
return radius;
}
Circle operator+(Circle ob) //add the two radius
{
Circle newob;
newob.radius = radius + ob.radius;
return newob;
}
bool operator > (Circle oc) //oc is object
{
return radius > oc.myRadius(); //compare radius
}
};
int main()
{
Circle c1, c2, c3;
c1.getRadius();
c2.getRadius();
c3 = c1 + c2;
cout << c1.myArea() << endl;
cout << c2.myArea() << endl;
cout << c3.myArea() << endl; //area with r3 = r1+r2
cout << c2.operator>(c1); //show 1 if Area-2 > Area-1
return 0; //show 0 if Area-1 > Area-2
}