Question

When to use function reference such as

void (&fr)() = foo;
fr();

instead of function pointer such as

void (*fp)() = &foo;
fp();

Is there something function pointer can't do but function reference can?

Was it helpful?

Solution

when you define a reference:

void (&fr)() = foo;
fr();

it gives you the ability to use fr almost everywhere where it would be possible to use foo, which is the reason why:

fr();
(*fr)();

works exactly the same way as using the foo directly:

foo();
(*foo)();

One more Difference is dereferencing a function reference doesn't result in an error where function pointer does not require dereferencing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top