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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.