Is it possible to have a pointer to function that has a definition, like the following. |
No, because a function pointer is not a function, it's a pointer.
In your example:
1 2 3 4 5 6 7 8 9 10 11
|
void Print();
void (*pt)();
int main()
{
pt = Print; // pt points to 'Print'
(*pt)(); // calls whatever pt points to... so this calls 'Print'
system("Pause");
return 0;
}
|
pt isn't a function in of itself and therefore cannot have a body.
EDIT:
@Techno01: That is a function which returns a pointer, which is a very different thing than a function pointer.
It's also wrong because it's returning a pointer to a local var which will immediately go out of scope.
EDIT2:
Just saw the other question:
Another question is should C++ programmers use function pointers? The only reason I ask is because most people on forums I go to usually disapprove of mixing C and C++ features together in one program. |
Function pointers are just as much a "C++ feature" as they are a "C feature", so yes it's OK to use them. Though many times you don't need to use them because abstract class interfaces provide similar functionality in an easier/safer manner.
C++11 even added a more robust 'function' object which can be used to hold function pointers. It makes them significantly easier to use, IMO.