0

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(); }
  }
Tom Mathew
  • 144
  • 1
  • 11
  • 1
    They have very different effect. – cpplearner Jun 02 '19 at 23:05
  • 2
    The whole point of `operator()` is to make an object look and act like a function. Yes, if you ignore the point of a feature, then the feature has no point. But if you don't start from the perspective that the intended point of a feature can be ignored, then... well, there's the point. I don't understand your question. – Nicol Bolas Jun 02 '19 at 23:08
  • 2
    Those two contexts are completely different. The former doesn't actually execute *anything*; it only declares an operator that *can*. The latter *always* executes on construction. If that fits your usage pattern, so be it, but they're very different things. – WhozCraig Jun 02 '19 at 23:16
  • 1
    One is so the object can be used as a functor, the other happens upon object construction. A constructed object that has a functor can be called over and over. A constructed object is constructed once. – Eljay Jun 03 '19 at 01:22

1 Answers1

2

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

  • 1
    Correct but you might want to clarify "by object"/"by class" which is unclear unless you know already know C++ well enough to know the answer. – curiousguy Jun 03 '19 at 01:36
  • I understand the usage now. Incidentally I now realize the difference of "by object" and "by class" – Tom Mathew Jun 03 '19 at 02:10