Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Function call operator ()

Parentheses () following an expression form a call with the supplied arguments. This syntax calls functions and callable objects; a class can provide it through an operator() member function.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

function(arguments...)
object(arguments...)
return_type operator()(parameters...) const;

The expression function(arguments...) calls a function. Commas separate arguments; function() supplies an empty argument list. Arguments initialize the corresponding parameters, and omitted arguments can be replaced by available default arguments. The same syntax works for a function pointer. Do not confuse a call such as f(x) with grouping (x) or a declaration such as int f(int);.

A class can define an operator() member function so that its objects can be called like functions. Such an object is often called a functor. Arguments participate in overload selection. In the example, shift(5) calls shift.operator()(5). The amount field stores object state, and the trailing const permits calling this member function on a const object.

Do not assume arguments are evaluated left to right: in C++23, initializations of different parameters are indeterminately sequenced relative to one another. The commas separating arguments are not comma operators.

The example prints 5 and 15, each on its own line. The eel.is source is an evolving working draft, not a frozen C++23 text; this explanation is limited to C++23-compatible rules.

Examples

#include <iostream>

int add(int a, int b) {
    return a + b;
}

struct Offset {
    int amount;

    int operator()(int value) const {
        return value + amount;
    }
};

int main() {
    const Offset shift{10};
    std::cout << add(2, 3) << '\n';
    std::cout << shift(5) << '\n';
}

Result

5
15

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources