0

I have understood the use of functors and how it works. But i am unable to undertand the following:

  1. What it means exactly when someone says "function objects have a state" ? Is this state not possible to maintain with normal functions? Can somebody explain with an example?

  2. When to prefer what: Function pointers vs functors vs normal functions?

anurag86
  • 209
  • 1
  • 3
  • 9

2 Answers2

1

1 What it means exactly when someone says "function objects have a state" ? Is this state not possible to maintain with normal functions?

It's not clear to me whether you mean "functions" or "functor objects" when you say "function objects".

Functions don't have state unless they have a static variable defined in the function scope. Example:

int getNextID()
{
   static int nextId = 0;
   return ++nextId;
}

However, functor objects -- i.e. instances of classes that are functors -- may have state, and many do. Example:

struct PrintFunctor
{
   PrintFunctor(std::ostream& out) : out_(out) {}

   template <typename T>
   void operator()(T const& obj) { out_ << obj << " "; }

   std::ostream& out_;
};

which can be used as:

PrintFunctor f(std::cout);
std::vector<int> v = { 1, 2, 3 };
std::for_each(v.begin(), v.end(), f);

You may want to note that since function's state is static it is shared with all calls of the function whereas you can have multiple functors that do the same thing but have different state. (Thanks are due to Nathan Oliver for bringing it up).

2 When to prefer what: Function pointers vs functors vs normal functions?

I don't see any difference between function pointers and normal functions. I am not sure what you meant by that.

My recommendation:

  1. Use normal functions when it doesn't need any state.
  2. Use functors when it needs state.
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • answer for 2nd question was succint – anurag86 Mar 13 '17 at 17:47
  • May want to note that since functions state is `static` that it shared with all calls of the function where you can have multiple functors that do the same thing but have different state. – NathanOliver Mar 13 '17 at 17:51
0

To answer your first question, normal functions can only maintain state through static variables, and in any case there is only one instance of a function. Thus it is not possible to have two or more instances of a function with different states, but this is eminently possible for a functor.

To answer your second question, these three types are really completely different and serve different purposes - your question is too broad.