Explanation of function pointers

Well, it is confusing a bit.

Function type and pointer to function type are indeed two different types (no more similar than int and pointer to int). However, there is a rule, that a function type decays to pointer to function type in almost all contexts. Here decaying loosely means converted (there is a difference between type conversion and decaying, but you are probably not interested in it right now).

What is important, is that almost every time you use a function type, you end up with pointer to function type. Note the almost, however – almost every time is not always!

And you are hitting some cases when it doesn’t.

typedef void(functionPtr)(int);
functionPtr fun = function;

This code attempts to copy one function (not the pointer! the function!) to another. But of course, this is not possible – you can’t copy functions in C++. The compiler doesn’t allow this, and I can’t believe you got it compiled (you are saying you got linker errors?)

Now, this code:

typedef void(functionPtr)(int);
functionPtr function;
function(5);

function does not shadow anything. Compiler knows it is not a function pointer which can be called, and just calls your original function.

Leave a Comment