Search code examples
c++stlstatefunctor

What exactly it means that functor in c++ have a state and other regular function doesnt have a state?


I am new to STL concepts in C++, and when I am going through a functor I have a struct, at that point the functor has a state, whereas other regular functions don't have state. What does it actually mean?

So far, I saw info that says a functor has state so it can access and store the data of its class where the operator() is overloaded, and other regular functions only can access the parameters passed to it as it doesn't have state.

But look at my following code:

class MyFuncPtr
{
public:
    int a;

    int operator ()(int b)
    {
        return a + b;
    }
    
    MyFuncPtr(int val)
    {
        a = val;
    }
    
    int sum(int b)
    {
        return a + b;
    }
};

int main()
{
    cout << "Hello World!\n";

    MyFuncPtr obj(5);

    int c = obj(15);

    int d = obj.sum(15);
}

Here with both functor and normal function, I can do the same thing, so what exactly does the functor having a "state" mean?


Solution

  • "State" refers to data that is remembered and carried between subsequent calls to a function or class method.

    Your MyFuncPtr is stateful, as it carries a data member a whose value is set in MyFuncPtr's constructor and is remembered and used through all calls to MyFuncPtr::operator(). You are setting the state once, and then using it over and over. You could just as easily update the state instead, by have MyFuncPtr::operator() save the new value into a and then expose another class method to retrieve the current value of a when needed.

    In your example, sum() is also stateful, as it is not a free function, it is actually a non-static member of MyFuncPtr, and thus has access to the same state data (MyFuncPtr::a) that MyFuncPtr::operator() has access to. A better example of a stateless sum() would look more like this instead:

    class MyFuncPtr
    {
    public:
        int a;
    
        int operator ()(int b)
        {
            return a + b;
        }
        
        MyFuncPtr(int val)
        {
            a = val;
        }
    };
    
    int sum(int a, int b)
    {
        return a + b;
    }
    
    int main()
    {
        cout << "Hello World!\n";
    
        MyFuncPtr obj(5);
        cout << obj(15) << endl;
    
        cout << sum(5, 15) << endl;
    }