Function Call Operator() Overloading in C++

By | September 29, 2021

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 arbitrary number of parameters in 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

People are also reading: 

Leave a Reply

Your email address will not be published. Required fields are marked *