An object that can be called like a function is known as a Function Object or a Functor.
In C++, an object of a class can be invoked like a function if it overloads the function call operator by defining the operator() member function.
The following is a simple example:
In the main() function above, the object s of type Simple is invoked like a function producing the output:
Output.1
Welcome to Functor in C++
When the function call s() is made, the compiler actually makes a call to the function s.operator()(). Cool, ain't it !!!
The following is another example that allows one to pass arguments:
A Functor can be passed as
an argument to another object for callback. In C, this would have been
accomplished through Function Pointers, while in C++ its more elegantly
done through Functors.
The following example illustrates the function callback ability using Functor:
The above could have also been achieved using a global function instead of a Functor.
The following code exhibits the same behavior using a global function:
The main advantage of using a Functor
over a global function is that a Functor can maintain state between
calls since it is an object. Instead of multiplying by 2, what if we
wanted to multiply by an arbitrary value ?
The following example depicts this scenario:
This would be messy to achieve with a global function. It would also not be thread-safe !!!
The C++ Standard Templates Library (STL) uses Functors extensively. Examples of some of the functors from STL are: less, negate, plus, greater, etc. The STL built-in functors are defined in the header .
The following example shows a simple example using STL functor less: