Operator Overloading/Relational Operator

Estimated reading: 2 minutes 32 Views

In C++, operator overloading allows you to redefine the behavior of operators such as arithmetic, logical, and relational operators for user-defined types. Relational operators are used to compare values between two operands and determine the relationship between them. Operator overloading for relational operators allows you to define custom comparison behaviors for objects of your own classes.

Purpose of Operator Overloading for Relational Operators:

  1. Custom Comparison: With operator overloading, you can define custom comparison behaviors for objects of your classes. This allows you to compare objects based on specific criteria relevant to your application domain.
  2. Natural Syntax: Overloaded relational operators enable you to use the familiar syntax of relational operators (<, <=, >, >=, ==, !=) with user-defined types. This improves code readability and makes your code more intuitive.

Example:

#include <iostream>
using namespace std;
class Relational {
        int x, y, z;
    public:
        Relational()
        {
            x = y = z = 0;
        }
        Relational(int i, int j, int k)
        {
            x = i;
            y = j;
            z = k;
        }
        int operator==(Relational b)
        {
            return(x == b.x && y == b.y && z == b.z);
        }
};
int main()
{
    Relational a(10, 10, 10), b(10, 10, 10);
    if (a == b)
        cout << "The two objects are equal\n";
    else
        cout << "The two objects are not equal\n";
    
    return 0;
}

This C++ code demonstrates operator overloading for the equality (==) operator in the Relational class.

  • The Relational class represents objects with three integer attributes x, y, and z.
  • The class provides two constructors: one default constructor that initializes all attributes to 0, and another constructor that allows initializing the attributes with provided values.
  • The operator= = function is overloaded inside the class. It takes another Relational object b as a parameter and returns an integer indicating whether the attributes of the two objects are equal. It checks if the x, y, and z attributes of both objects are equal and returns 1 if they are, and 0 otherwise.
  • In the main() function, two Relational objects a and b are created, both initialized with the values (10, 10, 10).
  • The overloaded equality operator == is used to compare objects a and b. If the attributes of both objects are equal, the message “The two objects are equal” is printed; otherwise, the message “The two objects are not equal” is printed.
Share this

Operator Overloading/Relational Operator

Or copy link

CONTENTS
English