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

Syntax:

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 (==)

#include<iostream>
#include<string.h>
using namespace std;

class date
{
char dt[15];
public:
void get()
{
cout<<"enter a date:";
cin>>dt;
}
char * operator == (date d2)//defining new new functionality for  == 
{
if(strcmp(dt,d2.dt)==0)
return "\ndates are equal";
else
return "\ndates are not equal equal";
}
};
main()
{
date d1,d2;
d1.get();
d2.get();
cout<<(d1==d2);//object comparision
}

O/P

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

 

Please Login/Signup to comment