-1

I was trying to make objects of a set and when I searched in StackOverflow I found a suggestion which worked: bool operator<(.....). What does this mean? And how is it different from bool operator ()?

I tried replacing < with () but it threw an error.

bool operator<(const hello &p1) const{}

(hello is a struct)

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    `i tried replacing < with () but it threw an error` Please edit and add an example of where `hello` is used and throwing an error. Where do you expect these to act the same? Also, the error itself would be nice too. –  Jul 27 '19 at 19:29
  • 1
    Possible duplicate of [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – JaMiT Jul 27 '19 at 20:13
  • What exactly does "throws an error" mean? The code runs and throws an error exception? The compiler doesn't like it? – gnasher729 Jul 27 '19 at 20:23

1 Answers1

1

operator()() is what I would call the "function operator". It makes the object behave like a function would, in the sense that I can use the same syntax as a function if I overload it:

class foo {
    bool operator()() {
       //...
   }
   // ...
};

// later...
bool myBool = myFoo();

As you can see, it acts like a function would.

operator<(), on the other hand, is a comparison operator. It allows me to use my foo in a comparison context, most commonly in if statements:

class foo {
    bool operator<(const foo& otherFoo) const {
       //...
   }
   // ...
};

// later...
if(myFoo1 < myFoo2) {
    //...
}


Edit:

I tried replacing < with () but it threw an error

Without knowing the context you are trying to use them in, it's hard to answer why, but it's good to know that these two not only aren't the same, but are usually used in very different contexts. You can't just change the < to a () and expect it to work. C++ doesn't work that way. You need to change the context the operators are used in, not just what operator your class has overloaded.