0

I'm currently learning basics of STL and I came to know that the '()' operator is overloaded. But I don't understand its functionality. I came across this code in which operator overloading is used. So can someone explain me how it works out?

class Node{
    public:
        int phy,chem,maths;
    Node(){
        phy = chem = maths = 0;
    }
};
class compare{
    public:
        bool operator()(Node &a,Node &b){
            if(a.phy < b.phy) return true;
        else if(a.phy > b.phy) return false;
        else{
            if(a.chem > b.chem) return true;
            else if(a.chem < b.chem) return false;
            else{
                if(a.maths <= b.maths) return true;
                else return false;
            }
        }
    }
};
mnskc
  • 11
  • Seems weird to flip the comparison direction on `chem` compared to `phy` and `maths`. Anyway looks like it's intended to be used as a comparator object for something like [std::sort](https://en.cppreference.com/w/cpp/algorithm/sort), specifically overloads 3 or 4 that take a comparator with `operator()` instead of just using `operator<` on the underlying type. – Nathan Pierson May 20 '21 at 04:30
  • Does this answer your question? [Understanding a Comparator functor for STL](https://stackoverflow.com/questions/48480562/understanding-a-comparator-functor-for-stl) – acraig5075 May 20 '21 at 06:04
  • I just don't understand the functionality provided here by overloading the "( )" operator . If we overload the "+" operator in case of some class then it may be used to sum up objects of the class , I want to know the functionality of overloading "( )" likewise – mnskc May 20 '21 at 07:27
  • Operators don't have a "functionality". You can make them whatever you want. You can overload + to do whatever you want (as long as it takes 2 objects and returns one). operator () simply looks like function invokation. If "foo" is an instance of compare then `foo(a, b)` is a valid syntax that's all, one can make operator () do whatever they want. Here in your example it seems it's comparing 2 `Node`s – al3c May 20 '21 at 08:56

0 Answers0