Daily Dose C++: Overload Comparison Operators

Wow, it has been a while since I wrote one of these. Need to find a way to incentivize myself on writing these as a habit. Anyways, let's talk C++.

One neat thing I remember from my Data Structures class was C++ comparison operator overloads. Pretty cool way to express these comparisons without having to write out a function call every time.

Say we have a custom class object to hold our data in.


class customObject{

private:

    int someValue;
    int anotherValue;
    string someName;

}

customObject co1, co2;

if (co1 > co2) return true;
// Most likely error out.

But the problem is that we can't just run a simple comparison operation on it.
How does the computer know if one customObject is greater than another if it has multiple variables within it?

So we can just overload the comparison operators in the class definition to tell the program these are the values we want to compare.

class customObject{

...

public:
    bool operator> (const customObject &co1, const customObject &co2){
        return co1.someValue > co2.someValue;
    }
    bool operator< (const customObject &co1, const customObject &co2){
        return co1.someValue < co2.someValue;
    }
}

In the code block above, we are assuming that someValue is the most meaningful value to compare. We don't care about the "anotherValue" variable, for example it could be an ID number.

You can overload pretty much any other operator.
To name a few: >=, <=, ==, ++, --

Source

https://www.learncpp.com/cpp-tutorial/overloading-the-comparison-operators/


You'll only receive email when they publish something new.

More from Wron
All posts