Thursday 8 March 2012

FUNCTION POINTERS


DEFINITION:
 A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior. For instance, every time you need a particular behavior instead of writing out a bunch of code, all you need to do is call the function. But sometimes you would like to choose different behaviors at different times in essentially the same piece of code.A function pointer always points to a function with a specific signature! Thus all functions, you want to use with the same function pointer, must have the same parameters and return-type!
          There are 2 types of function pointers:
1.Pointers to ordinary C functions or to static C++ member functions.
2.Pointers to non-static C++ member functions.
The basic difference is that all pointers to non-static member functions need a hidden argument.
SYNTAX:
                          void (*foo)(int);
 foo is a pointer to a function taking one argument, an integer, and that returns void. It's similar to  declaration of a function called "*foo", which takes an int and returns void. If *foo is a function, then foo must be a pointer to a function.
INITIALIZING: 
To initialize a function pointer,  the address of a function in program must be given to it. The syntax is like any other variable:

You can get the address of function simply by naming it.
                            void  foo();
                           func_pointer = foo;
or by prefixing the name of the function with an ampersand
                            void foo();
                           func_pointer = &foo;


INVOKING:
Invoke the function pointed similar to calling a function.
                        func_pointer( arg1, arg2 );

COMPARING FUNCTION POINTERS:
 The comparison-operators (==, !=) are used to compare function pointers.

USES:
1. Functions as Arguments to Other Functions
2.Callback Functions


BENEFITS:
Function pointers provide a way of passing around instructions for how to do something
You can write flexible functions and libraries that allow the programmer to choose behavior by               passing function pointers as arguments
This flexibility can also be achieved by using classes with virtual functions.




No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Labels