Open In App

How to Overload the Function Call Operator () in C++?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, operator overloading allows the user to redefine the behavior of an operator for a class. Overloading the function call operator () allows you to treat objects like functions enabling them to be called as if they were functions. Such classes are called functors in C++.

In this article, we will learn how to overload the () function call operator in C++.

Overloading Function call Operator () in C++

In C++, the function call operator () is overloaded by defining the member function named operator() inside a class. When an object of this class is used with the () operator, it will behave as a function executing the body of the member function operator(). 

C++ Program to Overload Function Call Operator

Now, let’s create a functor to check if a given year is a leap year. The functor will be callable to perform the check.

C++




// Program to demonstrate how to overload () operator
#include <iostream>
  
using namespace std;
  
class GFG {
public:
    // Overloading the function call operator to check leap
    // year
    bool operator()(int year) const
    {
        return ((year % 4 == 0 && year % 100 != 0)
                || (year % 400 == 0));
    }
};
  
int main()
{
    // Creating an instance of the GFG functor
    GFG isLeapYear;
  
    // Year to be checked
    int year = 2024;
  
    // Checking if the year is a leap year using the functor
    if (isLeapYear(year)) {
        cout << year << " is a leap year." << endl;
    }
    else {
        cout << year << " is not a leap year." << endl;
    }
    return 0;
}


Output

The Sorted array: 15 15 25 27 38 67 95 

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads