Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Functor and Pointer to Functor

📅 2010-Nov-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, functors, pointers ⬩ 📚 Archive

Functor

In C++, a functor is an object whose class has the operator () function. If we have an object foo of a functor class Foo, we can call the operator() function by simply foo().

class Foo
{
public:
    void operator() ()
    {
        cout << "What a fine day!" << endl;
    }
};

int main()
{
    Foo foo;
    foo();
    return 0;
}

Pointer to Functor

If we have a pointer to a functor, here are a few ways of calling the function through that pointer:

Foo* foo = new Foo();

// Using indirection operator to dereference the pointer
(*foo)();

// Using the member access operator
foo->operator()();

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧