How to Overload the Function Call Operator () in C++?
Last Updated :
07 Feb, 2024
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++
#include <iostream>
using namespace std;
class GFG {
public :
bool operator()( int year) const
{
return ((year % 4 == 0 && year % 100 != 0)
|| (year % 400 == 0));
}
};
int main()
{
GFG isLeapYear;
int year = 2024;
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
Share your thoughts in the comments
Please Login to comment...