Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Relational Operator Overloading in C++

Relational Operator Overloading in C++

Relational Operator Overloading

Relational operator overloading is frequently used to compare many of the built in data types in C++. We can overload relational operators like >,<,>=etc to directly manipulate the object of a class

Syntax:

return_type operator symbol(parameters)
{
   // function definition
}
Here operator is a keyword and relational operator symbol is the operator to be overloaded

Example 1

Overloading > i.e. greater than operator to know tallest student between two students.

#include<iostream>
using namespace std;

class Student{
    int feet = 0; //can be b/w 0 & infinity
    int inches = 0; // can be b/w 0 & 12
    
    public:
    void getHeight(int f, int i)
    {
        //feet can be b/w [0,infinity]
        //inches can be b/w [0,12)
        if(f >= 0 && (i >= 0 && i <12))
        {
            feet = f;
            inches = i;
        }
        else
        {
            cout << "Invalid height format" << endl;
            cout << "By default 0,0 will be taken" << endl;
        }
    }
    bool operator >(Student s2)
    {
        if(feet > s2.feet)
            return true;
        
        if(feet == s2.feet && inches > s2.inches)
        {
            return true;
        }
         
        return false;
    }
  
};

int main()
{
    Student s1,s2;
    
    s1.getHeight(5,10);
    s2.getHeight(6,1);
    
    if(s1 > s2)
        cout << "Student 1 is taller" << endl;
    else if(s2 > s1)
        cout << "Student 2 is taller" << endl;
    else
        cout << "Both have equal height" << endl;
    

    return 0;
}

Output –

Student 2 is taller

Overloading comparison Operator (==)

Her we are writing program to check if two clocks are showing the same time or not –

#include<iostream>
using namespace std;

class Time
{
    int hour, mins, secs;
    public:
    Time()
    {
        hour=0, mins=0; secs=0;
    }
    
    // parameterized constructor
    Time(int h, int m, int s)
    {
        if(h>=0 && h <=23 && m >=0 && m <=59 && s >0 && s <=59){
            hour=h, mins=m; secs=s;
        }
        else{
            cout << "Invalid time format, values would be 00:00:00 by default" << endl;
        }
    }
    
    bool operator ==(Time t2)
    {
        return ( hour == t2.hour && mins == t2.mins && secs == t2.secs);
    }
};


int main()
{
    Time t1(7,11,30);
    Time t2(3,30,41);

    if(t1 == t2)
    {
        cout << "Both clocks are showing the same time";
    }   
    else 
    {
        cout << "Clocks are showing differen times";
    }
    return 0;
}