Function-Object Classes with State

Like any other class, a function-object class can have additional members aside from operator(). Function-object classes often contain data members that are used to customize the operations in the call operator.

As an example, we’ll define a class that prints a string argument. By default, our class will write to cout and will print a space following each string. We’ll also let users of our class provide a different stream on which to write and provide a different separator. We can define this class as follows:

class PrintString {public:    PrintString(ostream &o = cout, char c = ' '):        os(o), sep(c) { }    void operator()(const string &s) const { os << s << sep; }private:    ostream &os;   // stream on ...

Get C++ Primer, Fifth Edition 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.