Understanding Function Objects in C++
Q: Can you explain the concept of function objects in C++ and how they are used to create reusable functions?
- C++
- Senior level question
Explore all the latest C++ interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create C++ interview for FREE!
Function objects, also known as functors, are a way to
create objects that can be used as functions. In C++, a functor is an object
that acts like a function and can be called using the function call operator ().
Functors are implemented as classes or structures that
define the function call operator. They can have state that is preserved
between calls, making them useful for creating reusable functions that maintain
some internal state.
Here is an example of a functor that returns the square of a
given number:
class Square { public: int operator()(int x) const { return x * x; } };
This functor can be used like a regular function:
Square square; int result = square(5); // returns 25
Functors can also take arguments:
class Add { public: Add(int n) : _n(n) {} int operator()(int x) const { return x + _n; } private: int _n; }; Add add5(5); int result = add5(3); // returns 8
In this example, the functor takes an integer argument n
in its constructor, and adds it to the integer argument x passed to its operator()
function.
Functors are often used with algorithms in the C++ Standard
Library, such as std::transform, to apply a function to each element of
a container. For example, here is how we can use the Square functor to
square each element of a vector:
c++Copy code
std::vector<int> v = {1, 2, 3, 4}; std::transform(v.begin(),
v.end(), v.begin(), Square());
This code applies the Square functor to each element
of the vector v, replacing each element with its square.


