As function pointers are also a pointer and null-equivalent for pointer types are nullptr
so you can assign the value to this default parameter as nullptr
.
Also, don't miss forget to add nullptr
check before using it.
void func(void (*additional_func) () = nullptr )
{
if(additional_func)
{
additional_func();
}
//some other code...
}
Also, it is more convenient to define an alias for this function-pointer as use like following:
using TPFunc = void (*) ();
void func( TPFunc additional_func = nullptr )
{
if(additional_func)
{
additional_func();
}
//some other code...
}
But it is best to use features from functional
header file instead of these raw-function-pointers. Following is an example to achieve this using functional
header file:
#include <iostream>
#include <functional>
using TPFunc = std::function<void()>;
void func( TPFunc additional_func = nullptr )
{
if(additional_func)
{
additional_func();
}
else
{
std::cout<< "Function pointer is `nullptr`\n";
}
//some other code...
}
void fun1()
{
std::cout << "In 'void fun1()'\n";
}
void fun2()
{
std::cout << "In 'void fun2()'\n";
}
int main()
{
func();
func(fun1);
func(fun2);
std::cout<< "Done";
return 0;
}
Output:
Function pointer is `nullptr`
In 'void fun1()'
In 'void fun2()'
Done