Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Functors
2.1.
How do we create functors?
3.
When do we use functors?
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Functors

Author Shreya Deep
0 upvote

Introduction

We know functions. A function in layman's English language denotes an activity. While in programming, it is a chunk of code that we write, which performs some operations. Also, in C++, we know what objects are! So, functors are a mixture of functions and objects. Let’s see how.

Also see, Literals in C.Fibonacci Series in C++

Functors

Functors are functions wrapped in a class so that it is available as an object. Now, what does this mean? 👀

We can say that a functor is a class that defines an operator. A functor lets you create objects which appear to be the same as functions. 

For example,

class Functors { 
public: int operator()(int x) {
 return x * 2;
} 
} 
Functors twice; 
int x = twice(5);
You can also try this code with Online C++ Compiler
Run Code


Explanation: You see what the code seems to be doing here. “Twice” is an object of the class Functors. In the class “Functors,” an operator function doubles the number passed in as the parameter and returns the result. So, when we create the object “Twice,” we can use it as a function, even though it’s not a function. It will do the same job for us. Therefore, we wrote twice(5), which will return 10. 

How do we create functors?

To create a functor, we create an object, which will overload the operator() from the class.

When do we use functors?

Suppose there is an array, and you want to add some value to its elements. Let’s say, in one instance, you want to add 1 to all the elements. And after this, in another instance, you want to add 4 to all the elements. How can you do it using the transform() function in STL? 

Well, it’s very easy to increment with one fixed value. Let’s say the value is 1. Then, we can do it as:

#include <bits/stdc++.h>
using namespace std;
   
int increment(int x) {  
return (x+1); 
}
   
int main()
{
    /* declare and initialise the array */
    int a[] = {6,7,8,9};
    int n = sizeof(a)/sizeof(a[0]);
    
/* using the transform() function to increment */
    transform(a, a+n, a, increment);
   /* Print the array */
    for (int i=0; i<n; i++)
        cout << a[i] <<" ";
   
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


But, now, how will we increment each element by 4?

Using the above increment function, we can’t. Also, we can’t add another parameter to the increment function, as the transform function doesn’t allow any other parameter to be passed. 

Therefore, here is when we will need functors. We can do this easily using functors. Let’s see how.

#include <bits/stdc++.h>
using namespace std;
  
/* Declaring a functor */
class increment
{
private:
    int number;
public:
    increment(int n) : number(n) { }
  
    /* Operator overloading */
    int operator () (int arr_num) const {
        return num + arr_num;
    }
};
  
 
int main()
{
    /* declaring and initialising an array */
    int a[] = {1, 2, 3, 4, 5};
    int n = sizeof(a)/sizeof(a[0]);
    int amount_of_increment= 5;
  
    /* incrementing using transform function. Also, sending the amount of increment as a parameter easily. */
    transform(a, a+n, a, increment(amount_of_increment));
  
    for (int i=0; i<n; i++)
        cout << a[i] << " ";
}
You can also try this code with Online C++ Compiler
Run Code

 

Try and compile with online c++ compiler.

Also See - Difference between argument and parameter

FAQs

  1. What is a function?
    A function is a set of all statements put together to perform a selected task. It could be statements doing some repeated duties or statements doing a little specialty task like printing etc.
     
  2. What is a class?
    A class is a user-defined data type that acts as a blueprint from which objects are created. A class has data members, which are data variables, and member functions which are functions used to manipulate these variables.
     
  3. What is an object?
    An object is defined as an entity that has a state and behavior. It is an instance of the Class. When a class is defined, initially, no memory is allocated to it, but when an object is created of that class, memory is allocated for it.
     
  4. What is operator overloading?
    Operator overloading provides us a flexible option for the creation of new definitions for most C++ operators. In C++, we can make an operator work for user-defined classes. In simple words, C++ has the ability to provide the operators with special meaning for a data type. This mechanism of giving such special meaning to an operator is known as operator overloading. Operator overloading is a compile-time polymorphism.
     
  5. When are functors useful?
    Functors are used in the case when we need to use an in-built STL function, but we’re restricted in terms of sending more than one parameter. Here, we can use functors and send the required parameters.

Key Takeaways

In this article, we learned about functors. We often used the concepts of functions and, objects classes. To learn more about operator overloading, refer to this. We hope this article helped you a lot! 

Are you planning to ace the interviews of reputed product-based companies like Amazon, Google, Microsoft, and more? 

Attempt our Online Mock Test Series on Coding Ninjas Studio now!

Happy coding!

Live masterclass