Item 18. Function Objects

Often you’ll need something that behaves like a function pointer, but function pointers tend to be unwieldy, dangerous, and (let’s admit it) passé. Often the best approach is to use a function object instead of a function pointer.

A function object, like a smart pointer (see Smart Pointers [42, 145]) is an ordinary class object. Whereas a smart pointer type overloads the -> and * (and possibly ->*) operators to mimic a “pointer on steroids,” a function object type overloads the function call operator, (), to create a “function pointer on steroids.” Consider the following function object that computes the next element in the well-known Fibonacci series (1, 1, 2, 3, 5, 8, 13, ...) with each call:

A function object is ...

Get C++ Common Knowledge: Essential Intermediate Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.