Functional Objects in c++

Could you please explain it with an example.

hello @Gurjot what you haven’t understood?
please elaborate your doubt .

Where functors are used?

Functors (Function Objects or Functionals) are simply put object + () .

In other words, a functor is any object that can be used with () in the manner of a function.

This includes normal functions, pointers to functions, and class objects for which the () operator (function call operator) is overloaded, i.e., classes for which the function operator()() is defined.

Sometimes we can use a function object when an ordinary function won’t work. The STL often uses function objects and provides several function objects that are very helpful.

Function objects are another example of the power of generic programming and the concept of pure abstraction. We could say that anything that behaves like a function is a function. So, if we define an object that behaves as a function, it can be used as a function.

For example, we could define a struct names absValue that encapsulates the operation of converting a value of type float to its absolute valie:


As we see from the definition, even though aObj is an object and not a function, we were able to make a call on that object. The effect is to run the overloaded call operator defined by the object absValue . The operator takes a float value and returns its absolute value. Note that the function-call operator must be declared as a member function.

So, Objects of class types, like the absValue object, that define the call operator are referred to as function object .

please tell if you don’t understand anything .

Check this code

what you have issue in this code ?

It’s written as comment in line no. 17


see this

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.