14.8. Function-Call Operator

Image

Classes that overload the call operator allow objects of its type to be used as if they were a function. Because such classes can also store state, they can be more flexible than ordinary functions.

As a simple example, the following struct, named absInt, has a call operator that returns the absolute value of its argument:

struct absInt {
    int operator()(int val) const {
        return val < 0 ? -val : val;
    }
};

This class defines a single operation: the function-call operator. That operator takes an argument of type int and returns the argument’s absolute value.

We use the call operator by applying an argument list to an absInt object in a way that looks like a function call:

int i = -42;
absInt absObj;      // object that has a function-call operator
int ui = absObj(i); // passes i to absObj.operator()

Even though absObj is an object, not a function, we can “call” this object. Calling an object runs its overloaded call operator. In this case, that operator takes an int value and returns its absolute value.


Image Note

The function-call operator must be a member function. A class may define multiple versions of the call operator, each of which must differ as to the number or types of their parameters.


Objects of classes that define the call operator are referred to as function objects. Such objects “act like functions” because we can call them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.35.185