O'Reilly logo

C++ Primer, Fifth Edition by Barbara E. Moo, Josée Lajoie, Stanley B. Lippman

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

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 ...

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