Users Online

· Guests Online: 43

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Operator Overloading Program in C++

Operator Overloading Program in C++

 

 

This C++ program overloads the == operator in the Circle Class. The Circle is a user-defined class with radius as its only data member and with provision of member function which computes the area of the circle. The overloaded == operator compares two circles on the basis of their radii, i.e. the circle would be equal to another circle if the radii of two circles are equal.

 

Here is the source code of the C++ program which overloads the == operator in the Circle Class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to overload == operator in circle class
  3.  */
  4.  
  5. #include <iostream>
  6. using namespace std;
  7.  
  8. class Circle {
  9.     private:
  10.         float radius;
  11.     public:
  12.         Circle(float r = 0) : radius(r) { }
  13.         void changeRadius(int radius) { this->radius = radius; }
  14.         float getRadius() { return radius; }
  15.         float getArea() const { return 3.14 * radius * radius; }
  16.         bool operator==(Circle a);
  17. };
  18.  
  19. inline bool Circle::operator==(Circle a)
  20. {
  21.     return this->radius == a.radius;
  22. }
  23.  
  24. int main()
  25. {
  26.     Circle A(10), B(20), C(10);
  27.  
  28.     cout << "Circle A : Radius = " << A.getRadius() << " units, Area = "
  29.          << A.getArea() << " sq. units\n";
  30.     cout << "Circle B : Radius = " << B.getRadius() << " units, Area = "
  31.          << B.getArea() << " sq. units\n";
  32.     cout << "Circle C : Radius = " << C.getRadius() << " units, Area = "
  33.          << C.getArea() << " sq. units\n";
  34.     cout << "A == B : ";
  35.     if (A == B)
  36.         cout << "Circles are equal.\n";
  37.     else
  38.         cout << "Circles are not equal.\n";
  39.     cout << "A == C : ";
  40.     if (A == C)
  41.         cout << "Circles are equal.\n";
  42.     else
  43.         cout << "Circles are not equal.\n";
  44. }

 

$ a.out
Circle A : Radius = 10 units, Area = 314 sq. units
Circle B : Radius = 20 units, Area = 1256 sq. units
Circle C : Radius = 10 units, Area = 314 sq. units
A == B : Circles are not equal.
A == C : Circles are equal.

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.78 seconds
10,818,317 unique visits