opCall()

Let’s move onto using the opCall() function to call objects as functions.

We'll cover the following

opCall() to call objects as functions

The parentheses around the parameter list when calling functions are operators as well. You have already seen how static opCall() makes it possible to use the name of the type as a function. static opCall() also allows creating objects with default values at run time.

On the other hand, non-static opCall() allows using the objects of user-defined types as functions:

Foo foo;
foo();

Above, the object foo is being called like a function.

As an example, let’s consider a struct that represents a linear equation. This struct will be used for calculating the y values of the following linear equation for specific x values:

y = ax + b

The following opCall() simply calculates and returns the value of y according to that equation:

struct LinearEquation {
    double a;
    double b;

    double opCall(double x) const {
        return a * x + b;
    }
}

With that definition, each object of LinearEquation represents a linear equation for specific a and b values. Such an object can be used as a function that calculates the y values:

Get hands-on with 1200+ tech skills courses.