Relational Operator Overloading in C++

Relational  operator overloading

  • Operator overloading is a compile polymorphic technique where a single operator can perform multiple tasks
  • As a result, the operator that is overloaded is capable to provide special meaning to the user-defined data types as well.

We can overload relational operators like >,<,>=etc to directly manipulate the object of a class


return_type::operator relational_operator_symbol(parameters)
// function definition

Here  operator is a keyword and relational  operator symbol is the operator to be overloaded

Relational Operator Overloading

Steps to perform Relational  operator overloading

  • Create the class and define its variables and member functions
  • Define the function get() to read strings
  • Define the function operator ==() to perform a comparison
  • Create the object for the class date  d1,d2 and call the function get() using these objects
  • call ==() upon these objects and return results accordingly

Overloading comparison Operator (==)

using namespace std;

class date
char dt[15];
void get()
cout<<"enter a date:";
char * operator == (date d2)//defining new new functionality for  == 
return "\ndates are equal";
return "\ndates are not equal equal";
date d1,d2;
cout<<(d1==d2);//object comparision


enter a date:24-07-1998 
enter a date:24-07-1998
dates are equal


Please Login/Signup to comment