C++ – Difference Between Functors and Functions
Last Updated :
17 Jan, 2023
In C++, we have multiple options to operate over the data like in the case where we can use functions and functors. Although both seem to be similar in a few ways but have multiple differences between them. Let’s check the differences between functions and functors in C++.
What are functions?
Functions are pieces of code that can be called from any other part of a program. They are a way of organizing code so that it is reusable, and can be used to perform a specific set of operations. Functions can be defined in any programming language and are typically used to encapsulate a set of instructions that can be called multiple times.
Example:
C++
#include <iostream>
using namespace std;
int add( int a, int b)
{
int c = a + b;
return c;
}
int main()
{
int a = 5, b = 6;
int c = add(a, b);
cout << c;
return 0;
}
|
What are functors?
Functors, also known as function objects, are objects that behave like functions. They are a type of object that can be treated like a function and can be used to encapsulate a set of instructions. They are similar to functions in that they can be used to encapsulate a set of operations, but they are different in that they can store states and can be used in more complex ways.
Example:
C++
#include <iostream>
using namespace std;
struct Add {
int a;
Add( int a)
: a(a)
{
}
int operator()( int b) { return a + b; }
};
int main()
{
Add add(5);
int c = add(6);
cout << c;
return 0;
}
|
Difference between functions and functors
Functors |
Functions |
Functors are objects that can be called like functions |
Functions are blocks of code that can be called by their name |
They can be created by defining the function call operator (operator()) |
They are created by declaring a function with a specific name and syntax |
They can store state and retain data between function calls |
Functions do not store state and do not retain data between calls |
They can be overloaded and customized to perform different tasks |
Functions cannot be overloaded and must have a fixed signature |
They can be passed as arguments to other functions or returned as results |
Functions can only be passed as arguments or returned as results |
They can have different types of arguments and return values |
Functions must have fixed types of arguments and return values |
They are slower to execute than functions due to their added complexity |
Functions are faster to execute due to their simplicity |
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...