Overloading Relational Operators in C++
Last Updated :
29 Jan, 2024
In C++, operator overloading is used to redefine the behavior of already existing operators. Similarly, overloading the relational operators is commonly used to compare the instances of user-defined classes. By overloading these operators we can easily define the behavior of comparisons for the objects of a given class.
In this article, we will see how to overload relational operators for a class in C++.
Relational Operator Overloading
Overloading a relational operator is similar to any other operator overloading. We can easily implement it by overloading “=="
operator and “<" operator
as member functions, and other relational operators can be derived from these.
C++ Program to Implement Relational Operator Overloading
The below example demonstrates how the overloading of relational operators is done in C++.
C++
#include <iostream>
using namespace std;
class MyClass {
private :
int value;
public :
MyClass( int val)
: value(val)
{
}
bool operator==( const MyClass& other) const
{
return value == other.value;
}
bool operator!=( const MyClass& other) const
{
return !(* this == other);
}
bool operator<( const MyClass& other) const
{
return value < other.value;
}
bool operator>( const MyClass& other) const
{
return value > other.value;
}
bool operator<=( const MyClass& other) const
{
return !(* this > other);
}
bool operator>=( const MyClass& other) const
{
return !(* this < other);
}
};
int main()
{
MyClass obj1(20);
MyClass obj2(20);
if (obj1 == obj2) {
cout << "obj1 is equal to obj2" << endl;
}
else {
cout << "obj1 is not equal to obj2" << endl;
}
if (obj1 < obj2) {
cout << "obj1 is less than obj2" << endl;
}
else {
cout << "obj1 is not less than obj2" << endl;
}
if (obj1 != obj2) {
cout << "obj1 is not equal to obj2" << endl;
}
else {
cout << "obj1 is equal to obj2" << endl;
}
if (obj1 > obj2) {
cout << "obj1 is greater than obj2" << endl;
}
else {
cout << "obj1 is not greater than obj2" << endl;
}
if (obj1 <= obj2) {
cout << "obj1 is less than or equal to obj2"
<< endl;
}
else {
cout << "obj1 is not less than or equal to obj2"
<< endl;
}
if (obj1 >= obj2) {
cout << "obj1 is greater than or equal to obj2"
<< endl;
}
else {
cout << "obj1 is not greater than or equal to obj2"
<< endl;
}
return 0;
}
|
Output
obj1 is equal to obj2
obj1 is not less than obj2
obj1 is equal to obj2
obj1 is not greater than obj2
obj1 is less than or equal to obj2
obj1 is greater than or equal to obj2
Explanation: In the above program the overloading of all the relational operators (==
, !=
, <
, >
, <=
, >=
) available in C++ is done for a custom class named MyClass
. It shows that how we can compare instances of user defined class with the help of
these operators in a manner way like using any primitive data types, which store an integer value.
Share your thoughts in the comments
Please Login to comment...