Monday, 12 August 2013

How to pass function-pointer to a function in c++?

How to pass function-pointer to a function in c++?

Here is three functions such as:-
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
now there is function which takes pointer to a function as one of the
argument:-
void Function_Pointer_func(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << " Result = "; // display result
cout << result << endl;
}
and to call the above function "Function_Pointer_func" the function is
written below
void Replace()
{
Function_Pointer_func(2, 5, /* pointer to function 'Minus' */
Plus);//// (1)
Function_Pointer_func(2, 5, /* pointer to function 'Minus' */
&Minus);//// (2)
}
Why does above function works fine as function "Function_Pointer_func"
takes function-pointer as argument. And if we replace RHS in line
float result = pt2Func(a, b); // call using function pointer
of function "Function_Pointer_func" by (*pt2Func)(a, b);then also it works
but for (&pt2Func)(a, b);
it gives an error of " error C2064: term does not evaluate to a function
taking 2 arguments " VS2008.
Now replace in the argument of "float (*pt2Func)(float, float)" in
function "Function_Pointer_func" by float (pt2Func)(float, float) then all
three
float result = pt2Func(a, b); //
float result = (&pt2Func)(a, b); //
float result = (*pt2Func)(a, b); //
statement works, why? I hope reason of my discomfort lies in understanding
the core understanding of function-pointer. Well, I am not presenting the
Q? without any good amount of reading but yes i haven't done any intensive
research on this so please feel free to recommend some reading in this
regard which will sort out my ambiguity.
Thanks for the help in advance.

No comments:

Post a Comment