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?
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, ...) .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With