Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Comparison using if else | Operator Overloading

I have to compare(>,<,==) two class object based upon different criteria, explained below.

class Student
{
    int iRollNumber;
    int iSection;
    int iMarks;
}
  1. I want to do comparison with iRollNumber, iSection, iMarks (Independently).
  2. I want to do comparison with iRollNumber, iSection (Combined).
  3. I want to do comparison with iMarks, iSection (Combined).
  4. ..........

Currently I am achieving this with GetMethods() and comparing them using if elseif elseif.. structure.

This is leading to the messy code everywhere!

If I use operator overloading I have to decide on one way of comparison.

Please suggest a way to do it with elegant coding.

Or

Can it be possible to call operator overloading Polymorphically?

like image 450
vrbilgi Avatar asked Feb 22 '26 08:02

vrbilgi


1 Answers

Write named functions:

int CompareR( const Student & a, const Student & b );
int CompareS( const Student & a, const Student & b );
int CompareM( const Student & a, const Student & b );
int CompareRS( const Student & a, const Student & b );
int CompareMS( const Student & a, const Student & b );

although the need to do so many different kinds of comparison on a class is a bit unusual - you normally only need one or perhaps two. The functions should return the same kind of values as strcmp() does:

<  returns -1
== returns 0
>  returns 1

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!