Search code examples
c++c++11operator-overloadingcallable-object

Why overload the () operator (callable operator) in a C++ class or struct when you could use a constructor?


Why would you overload the () operator in a C++ class or struct in C++11 or higher? As far as I can tell, these operators are overloaded when you want to pass objects like classes or structs into a std::thread and kick off a new thread with a package of data to go along with it, through a callable type. But other than that, why else would you overload the () operator? Couldn't you simply do the same things in the constructor for a class or struct?

Why use

  struct MyCallableStruct{
    void operator() () {
        dosomething();
    }
  }

when you could do

  struct MyCallableStruct{
      MyCallableStruct() { dosomething(); }
  }

Solution

  • They're totally different.

    First and most importantly, When you use operator(), it can be passed as function parameters (by object). In contrast, when implemented by constructor, it can only be passed through templates (by class)

    Second, operator() can be called several times after object created, while construtor can only be called at constructing

    All in all, they're different and useful in different scenarios