>

Functor in C++

Functors are also called function objects.Functors are class objects which can be treated as function itself.To achieve functor benefit a class must implement the oprator().The most important thing about Functors is the lifecycle, one can use a a functor’s constructor to store the attribute, which can be used later while implementing operator().

The best thing about functor is that they can contain attribute which was previously stored during constructor class.The normal function does not provides this benefit.

The best example to understand functor is provided below:-

class Functor
{
private:
int m;

public:
Functor (int n) : m(n) {}
int operator() (int p)
{
return m + p;
}

};

int main()
{
Functor add(10);
add(21); //functor call
return 0;
}

The output will be 31.
Clearly constructor was called and m was initialised with 10.When functor is called with value 21 it gets added to 10.

Another example

class Functor {
string name;
public:
Functor(const char *stringname) : name(stringname) {}
void operator()()
{
cout << "hello " << name << endl; } }; int main() { Functor func("Functor_Test"); func(); //functor call return 0; } Here output will be hello Functor_Test.

Leave a Reply