Search code examples
c++operator-overloadingcomparison-operators

Overloading comparison operators for different types in c++


I need to be able to compare one of my classes (which contains a lot more than an integer) to integers, even though that might be stretching the like of equality a little it's close enough...

How do I overload the equality operator for different types?

I basically have a class like this

struct MyClass {
    int start;
    int middle;
    int threequarters;
};

and the overloaded operator

inline bool operator==(const MyClass& lhs, const MyClass& rhs) {
    return lhs.middle == rhs.middle;
}

So when comparing with integers I need to compare against the middle variable as well, but I'm not sure if I need two sets of operator functions, one where integer is lhs and one where integer is rhs?

inline bool operator==(const int& lhs, const MyClass& rhs) {
    return lhs == rhs.middle;
}

inline bool operator==(const MyClass& lhs, const int& rhs) {
    return lhs.middle == rhs;
}

Solution

  • To clarify from my comment, this will support code so you can either provide all variations of operators:

    inline bool operator==(const MyClass& lhs, const MyClass& rhs) {
    return lhs.middle == rhs.middle;
    }
    
    inline bool operator==(const int& lhs, const MyClass& rhs) {
    return lhs == rhs.middle;
    }
    
    inline bool operator==(const MyClass& lhs, const int& rhs) {
    return lhs.middle == rhs;
    }
    

    And do that for every operator (which blows up into a significant amount of code). OR if it makes sense to, you can provide a constructor which constructs from int:

    struct MyClass {
    MyClass() {} // default
    MyClass( int x ) { /* init for an int here */ }
    int start;
    int middle;
    int threequarters;
    };
    

    If you do this, then you will only need the MyClass,MyClass version for each operator:

    inline bool operator==(const MyClass& lhs, const MyClass& rhs) {
    return lhs.middle == rhs.middle;
    }
    

    Because when the compiler sees:

    if ( 5 == my_class ) {}
    

    It actually does this:

    if ( MyClass(5).operator==( my_class ) ) {}