Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can it be useful to overload the "function call" operator?

Tags:

I recently discovered that in C++ you can overload the "function call" operator, in a strange way in which you have to write two pair of parenthesis to do so:

class A {    int n; public:    void operator ()() const;  }; 

And then use it this way:

A a; a(); 

When is this useful?

like image 987
lurks Avatar asked Feb 28 '10 02:02

lurks


People also ask

How do you overload a function call operator?

Unlike all other overloaded operators, you can provide default arguments and ellipses in the argument list for the function call operator. 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, ...) .

Why is it necessary to overload an operator?

The purpose of operator overloading is to provide a special meaning of an operator for a user-defined data type. With the help of operator overloading, you can redefine the majority of the C++ operators. You can also use operator overloading to perform different operations using one operator.

Which function is used to overload the operator?

An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but like overloaded functions, they are distinguished by the number and types of operands used with the operator.


1 Answers

This can be used to create "functors", objects that act like functions:

class Multiplier { public:     Multiplier(int m): multiplier(m) {}     int operator()(int x) { return multiplier * x; } private:     int multiplier; };  Multiplier m(5); cout << m(4) << endl; 

The above prints 20. The Wikipedia article linked above gives more substantial examples.

like image 114
Greg Hewgill Avatar answered Nov 05 '22 21:11

Greg Hewgill