37

How does C++ handle function pointers in relation to functions with defaulted parameters?

If I have:

void foo(int i, float f = 0.0f);
void bar(int i, float f);


void (*func_ptr1)(int);
void (*func_ptr2)(int, float);
void (*func_ptr3)(int, float = 10.0f);

Which function pointers can I use in relation to which function?

1
  • C++ does not allow default arguments in function pointer declarations. Your func_ptr3 declaration is ill-formed. So there's nothing to "handle" here. Commented Apr 7, 2021 at 13:39

2 Answers 2

36

Both foo() and bar() can only be assigned to func_ptr2.

§8.3.6/2:

A default argument is not part of the type of a function. [Example:

int f(int = 0);

void h() {
    int j = f(1);
    int k = f(); // OK, means f(0)
}

int (*p1)(int) = &f; 
int (*p2)() = &f; // error: type mismatch

--end example]

Sign up to request clarification or add additional context in comments.

4 Comments

because default parameter are actually implemented by compiler ?
Because default arguments are not taken into consideration for the type, i.e. int f(int) and int g(int=0) have the same type.
That would rule out func_ptr1. What about func_ptr3?
That also rules out #3 - default arguments are only allowed for function declarations.
1

Default argument cannot be provided for pointers to functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.