Function Call Operator() Overloading in C++

Posted in /  

Function Call Operator() Overloading in C++
vinaykhatri

Vinay Khatri
Last updated on April 18, 2024

    Using the concept of Operator Overloading we can overload the function call operator () , and when we say we can overload the function call operator () we do not mean we can redefine a new way to call a function, rather in function call operator overloading we redefine the parameters accepted by the function and after function call operator overloading we can pass an arbitrary number of parameters in a class member function. Example

    #include <iostream>
    using namespace std;
    
    class Displacement {
       private:
          int meters;  
       public:
          // required constructors
    
          Displacement() 
          {
             meters = 0;
          }
    
          Displacement(int m)
          {
             meters=m;
          }  
    
          // overload function call
    
          Displacement operator()(int a, int b, int c) 
           {
             Displacement D;
             D.meters = a+b+c;
             return D;
           } 
    
          // it show the displacement
          void show_displacement() 
            {
              cout  << meters << " Meters " << endl;
            }  
    };
    
    int main() {
       Displacement D1(100), D2;
       cout << "D1 Displacement : ";
       D1.show_displacement();
       D2 = D1(200, 200, 200); // invoke operator() overloading method
       cout << "D2 Displacement:";
       D2.show_displacement();
       return 0;
    }

    Output D1 Displacement: 100 Meters D2 Displacement: 600 Meters

    Conclusion

    So, this was all about function call operator() overloading in C++. When you overload the function call operator(), it does not mean that you create another way to call a function. Instead, you create an operator function that can accept an arbitrary number of parameters. We hope the example mentioned in this tutorial helped you develop a better understanding of how function call operator() overloading works in C++. Also, if you have any queries or suggestions, feel free to share them in the comments section below. People are also reading:

    Leave a Comment on this Post

    0 Comments