C++ offers a rich set of built-in comparison operators like == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to). These operators work seamlessly with built-in data types like integers, floats, and characters. However, when you create custom classes in C++, you might want to define how objects of that class should be compared based on their specific member variables. This is where overloading comparison operators comes in.
sort
and find
rely on overloaded comparison operators to order and search for elements within containers. By overloading these operators, you ensure your custom classes can be effectively used with such algorithms.The syntax for overloading comparison operators is similar for all comparison operators:
bool operator==(const ClassName &rhs) const;
Here, ClassName
is the name of the class, and rhs
is a reference to the object being compared against.
Let’s illustrate the implementation of overloading comparison operators with examples.
Consider a simple Point
class representing a point in 2D space.
#include
class Point {
private:
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
// Overloading equality operator (==)
bool operator==(const Point &rhs) const {
return x == rhs.x && y == rhs.y;
}
};
int main() {
Point p1(3, 4);
Point p2(3, 4);
Point p3(5, 6);
std::cout << "p1 == p2: " << (p1 == p2) << std::endl; // true
std::cout << "p1 == p3: " << (p1 == p3) << std::endl; // false
return 0;
}
// output //
p1 == p2: 1
p1 == p3: 0
Point
, which represents a point in 2D space with coordinates x
and y
.x
and y
coordinates. It has default parameter values of 0, so we can create points without specifying coordinates.==
) inside the Point
class.==
operator takes a const reference to another Point
object (rhs
) as a parameter.x
and y
coordinates of the current object (this
) with the coordinates of the object being compared (rhs
).true
; otherwise, it returns false
.In the main()
function, we create three Point
objects: p1
, p2
, and p3
, with different coordinates.
==
operator to compare pairs of points:p1 == p2
: This comparison evaluates to true
because p1
and p2
have the same coordinates.p1 == p3
: This comparison evaluates to false
because p1
and p3
have different coordinates.Overloading comparison operators in C++ allows customizing the comparison behavior for user-defined types. By providing custom implementations for these operators, we can define how objects of our classes are compared, enabling more intuitive and efficient code.Happy coding !❤️