Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers with default parameters in C++

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?

like image 981
user308926 Avatar asked Apr 05 '10 00:04

user308926


People also ask

Can C functions have default arguments?

C has no default parameters.

What is the default parameter of a function?

The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

What is default parameter in function explain with example?

Default values indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator. Below is a typical syntax for default argument. Here, foo parameter has a default value Hi! def defaultArg(name, foo='Come here!'

What rules apply for functions with default parameters?

Rule 1: creating functions. When programmers give a parameter a default value, they must give default values to all the parameters to right of it in the parameter list.


2 Answers

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]

like image 200
Georg Fritzsche Avatar answered Oct 11 '22 06:10

Georg Fritzsche


Default argument cannot be provided for pointers to functions.

like image 27
Dixit Singla Avatar answered Oct 11 '22 06:10

Dixit Singla