Function Pointers is a rather confusing yet powerful feature of C++ programming language. Even if you have programming for a while I bet you have seen nothing like it, simply because they aren't’t needed in everyday programming.
Their most common use is in writing compilers and interpreters.
The main theory behind function pointers is, just like the contents of a variable can be accessed by a pointer, much the same way functions can also be invoked (called) by referencing it by a pointer to that function.
Although variables and functions are two separate identities, both of these are stored at some memory address which can be pointed (and hence accessed) by a pointer.
Going in detail of the working of function pointers will only confuse you so we skip that for now and move on to a simple example program.
The function defined in the program is made as simple as possible to reduce confusions. Please note that the program only illustrates how function pointers are declared and used but program doesn't’t serve any practical purpose.
// -- Function Pointers -- // Example program to illustrate how // pointer to function are declared // and used #include<iostream.h> // function prototype void func (void); void main(void) { // note the declaration of // of the pointer. // pointer is declared with void data type // because function's return // type is void, the void in the // parenthesis is due to the function // taking no (void) argument void (*func_ptr) (void); // just as array name without indices // gives the address, same way // function name without parenthesis // gives the address of the function func_ptr=func; cout<<"Function accessed directly:\n"; func(); cout<<"Function accessed via pointer:\n"; (*func_ptr)(); } void func(void) { cout<<"Simplest of the simple function\n\n"; }
Good-Bye!
Related Articles: