You are on page 1of 2

Overloading function calls

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:

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : hrishikesh@impetusitservices.com | Website http://impetusits.in
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.

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : hrishikesh@impetusitservices.com | Website http://impetusits.in

You might also like