How to Overload the Less-Than (<) Operator in C++?
In C++ we have an operator called less than operator (<) which checks if the left side operand is smaller than the right side operand or not. In this article, we will learn how to overload the less-than operator in C++.
Overloading Less-Than Operator in C++
In C++, we can overload the less-than operator using the operator function declared as shown:
Syntax to Overload Less-Than Operator
bool operator<(const className& right) const;
Here, className is the name of the class and right is the name of the right-hand side operand.
C++ Program to Overload Less-Than Operator
The below program demonstrates how we can overload less-than operators using operator overloading in C++.
C++
// C++ program to overload the less than < operator #include <iostream> using namespace std; // creating class Coordinates class Coordinates { public : // constructor Coordinates( int x, int y) : x(x) , y(y) { } // Overloading the less-than operator for the Point // objects bool operator<( const Coordinates& other) const { return (x < other.x) || ((x == other.x) && (y < other.y)); } private : int x, y; }; int main() { // initializing two coordinates p1 and p2 Coordinates p1(1, 2); Coordinates p2(3, 4); // checking if p1 is less than p2 if (p1 < p2) { cout << "p1 is less than p2." << endl; } else { cout << "p1 is not less than p2." << endl; } return 0; } |
p1 is less than p2.
Explanation: In the above example, we are overloading the less than (<) operator to compare between the given points for that we first compare the x coordinates of two Points p1 and p2 and if they are equal then we compare the y coordinates, and return the smaller one.