Overloading function calls (C++ only)

The function call operator, when overloaded, does not modify how functions are called. Rather, it modifies how the operator is to be interpreted when applied to objects of a given type.

You overload the function call operator, operator(), with a nonstatic member function that has any number of parameters. If you overload a function call operator for a class its declaration will have the following form:

return_type operator()(parameter_list)

Unlike all other overloaded operators, you can provide default arguments and ellipses in the argument list for the function call operator.

The following example demonstrates how the compiler interprets function call operators:

struct A {
  void operator()(int a, char b, ...) { }
  void operator()(char c, int d = 20) { }
};

int main() {
  A a;
  a(5, 'z', 'a', 0);
  a('z');
//  a();
}

The function call a(5, 'z', 'a', 0) is interpreted as a.operator()(5, 'z', 'a', 0). This calls void A::operator()(int a, char b, ...). The function call a('z') is interpreted as a.operator()('z'). This calls void A::operator()(char c, int d = 20). The compiler would not allow the function call a() because its argument list does not match any function call parameter list defined in class A.

The following example demonstrates an overloaded function call operator:

class Point {
private:
  int x, y;
public:
  Point() : x(0), y(0) { }
  Point& operator()(int dx, int dy) {
    x += dx;
    y += dy;
    return *this;
  }
};

int main() {
  Point pt;

  // Offset this coordinate x with 3 points
  // and coordinate y with 2 points.
  pt(3, 2);
}

The above example reinterprets the function call operator for objects of class Point. If you treat an object of Point like a function and pass it two integer arguments, the function call operator will add the values of the arguments you passed to Point::x and Point::y respectively.

Related information