C++ - Function Call Operator Overloading
Function Call operator ( ), like the subscript operator, is considered a binary operator. function call operator can be overloaded for class objects and the declaration is identical to any binary operator. Overloading of (), does not modify how functions are called; rather, it modifies how the operator is to be interpreted when applied to class objects.
Example: overloading function call operator
In the example below, function call () operator is overloaded to assign the private data members of the vector class object.
#include <iostream> using namespace std; class vector { private: int x; int y; public: //function to display vector void displayVector() { cout<<"("<<x<<", "<<y<<")\n"; } //function for overloading () vector operator() (int a, int b) { x = a; y = b; return *this; } }; int main () { vector v1, v2; //objects with function call v1(10, 15); v2(5, 25); v1.displayVector(); v2.displayVector(); return 0; }
The output of the above code will be:
(10, 15) (5, 25)
❮ C++ - Operator Overloading