O'Reilly logo

Beginning C++ Programming by Richard Grimes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Defining function classes

A functor is a class that implements the () operator. This means that you can call an object using the same syntax as a function. Consider this:

    class factor     {         double f = 1.0;     public:         factor(double d) : f(d) {}         double operator()(double x) const { return f * x; }      };

This code can be called like this:

    factor threeTimes(3);        // create the functor object     double ten = 10.0;     double d1 = threeTimes(ten); // calls operator(double)     double d2 = threeTimes(d1);  // calls operator(double)

This code shows that the functor object not only provides some behavior (in this case, performing an action on the parameter) but it also can have a state. The preceding two lines are called through the operator() method on an object: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required