2.2 Function objects

The function-call operator. A function object is an object that has the function-call operator (operator() ) defined (or overloaded). These function objects are of crucial importance when using STL. Consider an example:


class less {
public:
   less (int v) : val (v) {}
   int operator () (int v) { 
      return v < val; }
private: 
   int val;
};

This function object must be created by specifying an integer value:


less less_than_five (5);

The constructor is called and the value of the argument v is assigned to the private member val. When the function object is applied, the return value of the overloaded function call operator tells if the argument passed to the function object is less than val:


cout << "2 is less than 5: " << (less_than_five (2) ? "yes" : "no");

Output: 2 is less than 5: yes

You should get familiar with this kind of programming, because when using STL you often have to pass such function objects as arguments to algorithms and as template arguments when instantiating containers, respectively.

Continue with section 2.3

Back to index


Johannes Weidl (J.Weidl@infosys.tuwien.ac.at) - Apr 16, 1996