Search code examples
c++operator-overloadingfunction-call-operator

What does void Classname::operator()(){ .... } do?


Im working my way through some C++ code and came across the following

void Classname::operator()()
{   
    //other code here
}

I assume this has something to do with overloading the constructor, but can someone elaborate on that?


Solution

  • operator() is the function-call operator. It allows you to use a class instance like a function:

    Classname instance;
    instance(); //Will call the overload of operator() that takes no parameters.
    

    This is useful for functors and various other C++ techniques. You can essentially pass a "function object". This is just an object that has an overload of operator(). So you pass it to a function template, who then calls it like it were a function. For example, if Classname::operator()(int) is defined:

    std::vector<int> someIntegers;
    //Fill in list.
    Classname instance;
    std::for_each(someIntegers.begin(), someIntegers.end(), instance);
    

    This will call instance's operator()(int) member for each integer in the list. You can have member variables in the instance object, so that operator()(int) can do whatever processing you require. This is more flexible than passing a raw function, since these member variables are non-global data.