C++ Tutorial C++ Advanced C++ References

C++ - Relational Operator Overloading



Relational operators are those operators which compares two operand, like operators (==, <, >, <=, >=) compares C++ data types. C++ allows us to specify these operators with a special meaning for a class object.

Example: overloading relational operators

In the example below, relational operators < and > are overloaded. When it is applied with point objects, it compares its distance from origin and returns true or false based on the comparison result. For example:

  • (10, 15) > (5, 25) will compare 10² + 15² > 5² + 25² which is equivalent to 325 > 650, hence returns false.
  • (10, 15) < (12, 14) will compare 10² + 15² < 12² + 14² which is equivalent to 325 < 340, hence returns true.

Note: In this example, cmath function hypot is used to calculate distance of a point from the origin.

#include <iostream>
#include <cmath>
using namespace std;
 
class point {
  public:
    int x, y;

    //class constructor
    point(){}
    point(int x, int y) {
      this->x = x;
      this->y = y;
    }     
};

//function for overloading <
string operator< (const point p1, const point p2) {
  float d1 = hypot(p1.x, p1.y);
  float d2 = hypot(p2.x, p2.y);
  return d1 < d2? "true" : "false";
} 

//function for overloading >
string operator> (const point p1, const point p2) {
  float d1 = hypot(p1.x, p1.y);
  float d2 = hypot(p2.x, p2.y);
  return d1 > d2? "true" : "false";
}   

int main () {
  point p1(10, 15), p2(5, 25), p3(12, 14);

  cout<<"(p1 > p2) returns: "<<(p1 > p2)<<"\n";
  cout<<"(p1 < p3) returns: "<<(p1 < p3)<<"\n";
  return 0;
}

The output of the above code will be:

(p1 > p2) returns: false
(p1 < p3) returns: true

❮ C++ - Operator Overloading