Clarification of Function Objects

Let's start with the definition of a function object: A function object is an instance of a class or structure that defines the parenthesis operator as a member function.

To clarify: A function object is NOT a function.  It looks like a function when you use it, but that is because your structure or class has overloaded the ( ) operator.  Because it is an instance of a class or structure, it can hold values between calls.

Now we know what a function object is.

Three reasons to use function objects in place of ordinary functions are to 1) to allow a function object to access or set state information that is held by an object, 2) to improve execution by using inline function calls or 3) modify the functionality of an STL algorithm. These reasons were not listed in order of importance or frequency of use. Reason 3 is probably the most important/frequent.

Here are a couple of examples of using a function object with the STL. The first example uses plus() to compute the by-element addition of two lists of integer values, placing the result into a plus() function object. This can be performed by the following:

 
   plus result = for_each (listOne.begin(), listOne.end(), plus() );
         

The second example negates every element in a vector of boolean values:

 
  transform(aVec.begin(), aVec.end(), aVec.begin(), logical_not() );