Function Object

Many of the STL algorithms have a parameter which is a function, for_each( ) and transform( ) being prime examples. That functional parameter doesn't have to be an actual function. It can be an object that behaves like a function. Such an object is called a "function object" or "functor".

A function is something that can be called using the parenthese and passing arguments -- myFunction( arg1, arg2). We can make objects behave this way by overloading operator( ).

But why would we want to do this?
Function objects are like "smart functions".

Below is an example used to add an integer value class Add { public: // const Add (int value) : m_value( value ) { } void operator( ) (int& n ) const { n += m_value; } private: int m_value; // value to add }; int main ( ) { set<int> iSet; // insert some data for (int i = 1; i < 10; i++) iSet.insert( i ); // print elements // 1 2 3 4 5 6 7 8 9 // create a function which adds 42 to its parameter Add add42( 42 ); // add 42 to each element of the set for_each( iSet.begin(), iSet.end(), add42 ); // print the elements // 43 44 45 46 47 48 49 50 51 }; In this example, a random number generator class remembers and uses the last number generated to create the next one. class RNG // Random Number Generator { public: RNG (unsigned int seed = 1) : m_lastValue( seed ) { }; unsigned int operator( ) () { // modify last Value for new value m_lastValue = some computation using m_lastValue return m_lastValue; } private: unsigned int m_lastValue; }; int main ( ) { RNG rng ( 42 ); for (int i = 0; i < 10; i++) cout << rng() << endl; }


Last Modified: Monday, 20-Nov-2006 15:15:10 EST