1

I understand in order to pass a function as arguments we need to make it a function pointer. But why do we need to pass function pointer as an argument in another function, while we can call the function in another function definition?

//Why this
int (*f1)(int);
int testFunction(int (*f)(int));

//Instead of this
int f1(int);
int testFunction()
{
     int f1Value = f1(2); //call the fucntion and store the value
}

the example might mean nothing.

When we favor passing function pointer instead of just calling the function?

Glenio
  • 122
  • 8

3 Answers3

2

When we favor passing function pointer instead of just calling the function?

When we want polymorphism.

In the direct call case, it is always the same function that is called (given that the wrapper function does nothing else, it appears to be rather redundant.)

In the case of function pointer, a different function can be called for any invokation of testFunction by assigning the pointer.

Note that function pointer is not the only way to achieve polymorphism. Others include function objects (for static polymorphism) and virtual functions (for OOP style structured runtime polymorphism).

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

It's a special time to need send a function-pointer as a parameter in C++, You can see the sort function which take another function for comparing elements.
Or in some low-level APIs function-pointer use for function call back, something like this in libusb which is call the function when work is down from background event.

Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32
1

To reduce duplicate codes.

For example, when you want to write the "map" function in python. It iterates all element in tuple then apply the function to the element.

This method very popular in C because it lacks of OOP. In C++, I think we can achieve the same effect with OOP but in some cases, it is more readable.

Che Huu
  • 163
  • 10