user2472862 user2472862 - 2 months ago 13
C++ Question

Why are function objects better than function pointers?

from Wikipedia - Function object


A typical use of a function object is in writing callback functions. A callback in procedural languages, such as C, may be performed by using function pointers.[2] However it can be difficult or awkward to pass a state into or out of the callback function. This restriction also inhibits more dynamic behavior of the function. A function object solves those problems since the function is really a fa├žade for a full object, carrying its own state.



  1. Why do function pointers make it difficult to pass a state into or out of the callback function and dynamic behavior of the function?

  2. if function do not use function pointer how programs can called function


Answer
  1. As far as function pointers in C go, you need to pass the state as an extra parameter. That's in opposition to languages like python, javascript or C++ that have closures. And that means storage duration needs to be considered for that extra structure.

  2. C programmers do make use of function pointers. And you can't write very generic code without using function pointers. We just apply discipline and pass the captured state in a structure, as a function parameter.

Comments