How to Overload the Less-Than (<) Operator in C++?
Last Updated :
12 Feb, 2024
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++
#include <iostream>
using namespace std;
class Coordinates {
public :
Coordinates( int x, int y)
: x(x)
, y(y)
{
}
bool operator<( const Coordinates& other) const
{
return (x < other.x)
|| ((x == other.x) && (y < other.y));
}
private :
int x, y;
};
int main()
{
Coordinates p1(1, 2);
Coordinates p2(3, 4);
if (p1 < p2) {
cout << "p1 is less than p2." << endl;
}
else {
cout << "p1 is not less than p2." << endl;
}
return 0;
}
|
Output
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.
Share your thoughts in the comments
Please Login to comment...