Overloading relational operator(<,>,<=,>=,==,!=)
Example:1
compare two objects using overloaded operator “<“.
// to overload < operator
// to compare the values of two objects
#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
int a;
public:
sample();
sample(int n);
void get();
void disp();
int operator<(sample s);
};
sample::sample()
{
a=0;
}
sample::sample(int n)
{
a=n;
}
void sample::get()
{
cout<<"Enter the value of a ";
cin>>a;
}
void sample::disp()
{
cout<<"a= "<<a<<endl;
}
int sample::operator<(sample s)
{
return(a<s.a);
/*
if (a<s.a)
return(1);
else
return(0);
*/
}
int main()
{
sample s1,s2;
s1.get();s2.get();
s1.disp();s2.disp();
int t;
t=s1<s2; //t=s1.operator<(s2);
if (t==1)
cout<<"the object s1 is less than object s2"<<endl;
else
cout<<"the object s1 is not less than object s2"<<endl;
getch();
return(0);
}
Output:
Enter the value of a 10
Enter the value of a 52
a= 10
a= 52
the object s1 is less than object s2
Example:2
compare two objects using overloaded operator “<=“.
// to overload <= operator
// to compare the values of two objects
#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
int a;
public:
sample();
sample(int n);
void get();
void disp();
int operator<=(sample s);
};
sample::sample()
{
a=0;
}
sample::sample(int n)
{
a=n;
}
void sample::get()
{
cout<<"Enter the value of a ";
cin>>a;
}
void sample::disp()
{
cout<<"a= "<<a<<endl;
}
int sample::operator<=(sample s)
{
return(a<=s.a);
/*
if (a<=s.a)
return(1);
else
return(0);
*/
}
int main()
{
sample s1,s2;
s1.get();s2.get();
s1.disp();s2.disp();
int t;
t=s1<=s2; //t=s1.operator<=(s2);
if (t==1)
cout<<"the object s1 is less than or equal to object s2"<<endl;
else
cout<<"the object s1 is not less than or equal to object s2"<<endl;
getch();
return(0);
}
Output:
Enter the value of a 25
Enter the value of a 63
a= 25
a= 63
the object s1 is less than or equal to object s2
Example:3
compare two objects using overloaded operator “>“.
// to overload > operator
// to compare the values of two objects
#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
int a;
public:
sample();
sample(int n);
void get();
void disp();
int operator>(sample s);
};
sample::sample()
{
a=0;
}
sample::sample(int n)
{
a=n;
}
void sample::get()
{
cout<<"Enter the value of a ";
cin>>a;
}
void sample::disp()
{
cout<<"a= "<<a<<endl;
}
int sample::operator>(sample s)
{
return(a>s.a);
/*
if (a>s.a)
return(1);
else
return(0);
*/
}
int main()
{
sample s1,s2;
s1.get();s2.get();
s1.disp();s2.disp();
int t;
t=s1>s2; //t=s1.operator>(s2);
if (t==1)
cout<<"the object s1 is greater than object s2"<<endl;
else
cout<<"the object s1 is not greater than object s2"<<endl;
getch();
return(0);
}
Output:
Enter the value of a 25
Enter the value of a 6
a= 25
a= 6
the object s1 is greater than object s2




