Function Call Operator Overloading in C++

Function Call Operator Overloading in C++

How to overload function call operator in C++?

The operator “()” is known as function call operator. When a function call operator is overloaded it does not modify how functions are called but, it modifies how the operator is to be explained when passed through objects of a given type.

Function call operator overloading is a sub part of operator overloading in C++. On this page, we will learn more about function call operator overloading in C++. But if you want to know more about operator overloading click the button below.

Function call operator overloading in C++

  • Function call operator is overloaded by instance  of the class and it is also known as function object.
  • When we overload function call operator, we are not creating a new way to call a function. But, we are creating an operator function that can be passed a number of parameters.
  • It only modifies how the operator is to be fetched by the object.

Syntax for function call operator overloading in C++

class class_name
{ 
    public: 
        void operator ()(); 
};

Program to overload function call operator in C++

Run
#include <iostream>
using namespace std;
 
class Length
{
   private:
      int kmeter;                   
      int meter;           
      
      
   public:
      Length()//Constructor. 
      {
         kmeter = 0;
         meter = 0;
      }
      Length(int km, int m) 
      {
         kmeter = km;
         meter = m;
      }
      
      
      Length operator()(int x, int y, int z)//Overload function call operator.
      {
         Length l;
         
         l.kmeter = x + z + 10;
         l.meter = y + z + 100 ;
         return l;
      }
      
      //Method to display length.
      void disLength() {
         cout << kmeter <<"Km " << meter << "M" << endl;
      }   
};

int main() 
{   
   Length l1(1, 112), l2;

   cout << "First length: "; 
   l1.disLength();

   l2 = l1(6, 7, 8); //Invoking function call operator.
   cout << "Second length:"; 
   l2.disLength();

   return 0;
}

Output:

First length: 1Km 112M
Second length:24Km 115M

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription