Skip to Main Content
C++ Primer Plus, Fourth Edition
book

C++ Primer Plus, Fourth Edition

by Stephen Prata
November 2001
Beginner content levelBeginner
1128 pages
29h 12m
English
Sams
Content preview from C++ Primer Plus, Fourth Edition

Function Objects (aka Functors)

Many STL algorithms use function objects, also known as functors. A functor is any object that can be used with () in the manner of a function. This includes normal function names, pointers to functions, and class objects for which the () operator is overloaded, that is, classes for which the peculiar-looking function operator()() is defined. For example, you could define a class like this:

class Linear
{
private:
    double slope;
    double y0;
public:
    Linear(double _sl = 1, double _y = 0)
        : slope(_sl), y0(_y) {}
    double operator()(double x) {return y0 + slope * x; }
};

The overloaded () operator then allows you to use Linear objects like functions:

 Linear f1; Linear f2(2.5, 10.0); double y1 = f1(12.5); // rhs is f1.operator()(12.5) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ Primer Plus, Fifth Edition

C++ Primer Plus, Fifth Edition

Stephen Prata
C++ All-In-One For Dummies®, 2nd Edition

C++ All-In-One For Dummies®, 2nd Edition

John Paul Mueller, Jeff Cogswell
C++ Primer Plus

C++ Primer Plus

Stephen Prata

Publisher Resources

ISBN: 0672322234Purchase book