In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function). In some languages, particularly C++, function objects are often called functors (not related to the functional programming concept).
A typical use of a function object is in writing callback functions. A callback in procedural languages, such as C, may be performed by using function pointers. However it can be difficult or awkward to pass a state into or out of the callback function. This restriction also inhibits more dynamic behavior of the function. A function object solves those problems since the function is really a façade for a full object, carrying its own state.
Many modern (and some older) languages, e.g. C++, Eiffel, Groovy, Lisp, Smalltalk, Perl, PHP, Python, Ruby, Scala, and many others, support first-class function objects and may even make significant use of them. Functional programming languages additionally support closures, i.e. first-class functions that can 'close over' variables in their surrounding environment at creation time. During compilation, a transformation known as lambda lifting converts the closures into function objects.
Consider the example of a sorting routine that uses a callback function to define an ordering relation between a pair of items. The following C/C++ program uses function pointers:
#include
/* qsort() callback function, returns < 0 if a < b, > 0 if a > b, 0 if a == b /
int compareInts(const void a, const void* b)
{
return ( *(int *)a - *(int *)b );
}
// prototype of qsort is
// void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));
int main(void)
{
int items[] = { 4, 3, 1, 2 };
qsort(items, sizeof(items) / sizeof(items[0]), sizeof(items[0]), compareInts);
return 0;
}
In C++, a function object may be used instead of an ordinary function by defining a class that overloads the function call operator by defining an operator() member function.