Overloading Relational Operators in C
Overloading Relational Operators in C
return 0;
}
Explanation
1. Overloading ==:
o bool operator==(const Person& other) const
o Compares both name and age to check if the objects are equal.
o The const keyword ensures that the method doesn’t modify the
objects.
2. Overloading <:
o bool operator<(const Person& other) const
o Compares the age of the two Person objects to determine their
relative ordering.
3. Output:
p1 is equal to p3
p1 is younger than p2
Using Friend Functions for Relational Operators
If symmetry is needed, such as comparing a non-class object with a class
object, you can use friend functions. Here’s an example:
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
// Friend function to overload '!='
friend bool operator!=(const Person& p1, const Person& p2);
// Friend function to overload '>='
friend bool operator>=(const Person& p1, const Person& p2);
void display() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
// Overload '!=' operator
bool operator!=(const Person& p1, const Person& p2) {
return !(p1.name == p2.name && p1.age == p2.age);
}
// Overload '>=' operator
bool operator>=(const Person& p1, const Person& p2) {
return p1.age >= p2.age;
}
Guidelines for Relational Operator Overloading
1. Consistency:
o When overloading relational operators, ensure consistency
among them. For example, if == is overloaded, != should also be
defined.
o Similarly, if < is overloaded, overload >, <=, and >= for
complete functionality.
2. Symmetry:
o Relational operators should behave symmetrically (e.g., a < b
should imply !(b < a)).
3. Return Type:
o Always return a bool for relational operators.
4. Const Correctness:
o Use const to ensure the objects being compared are not
modified.
Extending: Overloading All Relational Operators
Here’s an example of overloading all six relational operators for a Rectangle
class based on area:
#include <iostream>
using namespace std;
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
int area() const { return width * height; }
bool operator==(const Rectangle& other) const { return area() ==
other.area(); }
bool operator!=(const Rectangle& other) const { return area() !=
other.area(); }
bool operator<(const Rectangle& other) const { return area() <
other.area(); }
bool operator>(const Rectangle& other) const { return area() >
other.area(); }
bool operator<=(const Rectangle& other) const { return area() <=
other.area(); }
bool operator>=(const Rectangle& other) const { return area() >=
other.area(); }
};
int main() {
Rectangle r1(4, 5);
Rectangle r2(3, 6);
if (r1 > r2)
cout << "r1 has a larger area than r2" << endl;
else
cout << "r1 does not have a larger area than r2" << endl;
return 0;
}
This ensures complete support for all relational operators.