Function pointer with default arguments | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Function pointer with default arguments

Please refer below code : #include <iostream> using namespace std; int sum(int a , int b = 5) { return a + b; } int main() { int (*fp)(int ,int);//function pointer fp = &sum; //int result = fp(3,5); int result = fp(3); cout << result; return 0; } I am not able to call function pointer with default argument. Is there any other way we need to declare function pointer with default argument?

10th Jan 2019, 5:05 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
8 Answers
+ 5
It seems default parameters mean something only to us and the compiler. They play no part in the function signature, and thus are ignored when you assign the function to a function pointer or a std::function object. Here are more details on the same: https://stackoverflow.com/questions/2576411/function-pointers-with-default-parameters-in-c https://stackoverflow.com/questions/10718994/can-i-bind-to-a-function-that-takes-default-arguments-and-then-call-it You can maybe define a class that stores the previous state of the argument and in case no new argument is provided, you use the old argument.
10th Jan 2019, 7:03 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 5
/*Fill in the blanks to declare a function sum returning the sum of its arguments and declare a function pointer psum pointing to sum.*/ int sum(int a, int b) { return a + b; } int (*psum)(int, int) = sum;
8th Jun 2020, 5:28 AM
vishwakarma kumar
vishwakarma kumar - avatar
+ 2
// suppose f1, f2, and f3 are declared void (*funcs[3])() = {f1, f2, f3}; for (int ix = 0; ix < ; ix++) { [ix](); }
1st Oct 2022, 5:12 AM
PRAVEEN KUMAR N
PRAVEEN KUMAR N - avatar
0
int sum(int a, int b) { return a b; } int ( psum)(int, ) = ;
14th Apr 2020, 8:05 AM
Ahmat Josi
0
declare a function sum returning the sum of its arguments and declare a function pointer psum pointing to sum. int sum(int a, int b) { return a + b; } int (*psum)(int,int) =sum;
29th May 2020, 8:45 AM
Vaibhav Chaudhary
Vaibhav Chaudhary - avatar
0
int sum(int a, int b) { return a + b; } int ( * psum)(int, int ) = sum ;
17th Dec 2020, 5:15 AM
Jeevanantham P
Jeevanantham P - avatar
0
void (*funcs[3])() = {f1, f2, f3}; for (int ix = 0; ix < ; ix++) { [ix](); }
1st Oct 2022, 5:10 AM
PRAVEEN KUMAR N
PRAVEEN KUMAR N - avatar
0
void (*funcs[3])() = {f1, f2, f3}; for (int ix = 0; ix < ; ix++) { [ix](); }
1st Oct 2022, 5:11 AM
PRAVEEN KUMAR N
PRAVEEN KUMAR N - avatar