An interesting c++ operator overload

// C++ program to demonstrate working of 
// functors. 
#include <bits/stdc++.h> 
using namespace std; 
  
// A Functor 
class increment 
{ 
private: 
    int num; 
public: 
    increment(int n) : num(n) {  } 
  
    // This operator overloading enables calling 
    // operator function () on objects of increment 
    int operator (a) (int arr_num) const { 
        returnnum + arr_num; }};// Driver code 
int main(a) 
{ 
    int arr[] = {1.2.3.4.5}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    int to_add = 5; 
  
    transform(arr, arr+n, arr, increment(to_add)); 
  
    for (int i=0; i<n; i++) 
        cout << arr[i] << ""; 
} 
Copy the code

The fourth argument received by transform takes advantage of operator overloading. Instead of passing in a unary function or pointer to a unary function, the transform now has a function-like effect with an object and the operator “()” overload.

This linetransform(arr, arr+n, arr, increment(to_add)); Same as the following two lines// Creating object of increment
increment obj(to_add); 

// Calling () on object
transform(arr, arr+n, arr, obj); 
Copy the code