Introduction
Function pointers, pointers are just a block of memory that point to another block of memory that actually hold the data, class, function etc. but the pointer can be altered to point to a dfferent block of memory. The best thing about pointers is that are capable of doing the same thing on the data referenced in the pointer.
A function pointer, is able to point to a function and call that function with the same similar parameters but then if the pointer reference is re-directed to another method it will still call in a same way and have the same parameters passed to it but just calling a different function.
Declaring a function pointer
To declare a function pointer
returntype (*functionpointername)(parameters);
as you can tell the declaration is very similar to a standard function, return type function name and parameters but in this case you have a * (pointer) to a function.
The return type and parameters example
int (*intAddSum)(int value1, int value2) = NULL;
In the above it will return a int with adding the two int parameters,it is always a good idea to set the function pointer to a NULL, you may not know where the default memory reference may goto!!!.
Basic example of a function pointer
Here is a basic example of a function pointer, it will point to a method that will take 2 parameters and add them up to return there sumed valued.
int addTwo(int value1, int value2)
{
return (value1 + value2);
}
int (*fPointer)(int , int) = NULL;
int main()
{
// the function pointer will take the address/reference (&) of the funtion addTwo
fPointer fP = &addTwo;
// call just a normal function.
fPointer(3,5);
return 0;
}
Full code of changing the pointer
Here is some full code that will change the pointer reference and also pass the function pointer to another method to be called from within there, so you can also pass function pointers, c++ is a great language to code in.
#include <iostream>
using namespace std;
void normalHi()
{
cout << "hi" << endl;
}
void normalBye()
{
cout << "bye" << endl;
}
// always set the function pointer to NULL.
void (*func)() = NULL;
// to pass a function pointer to a function.
void callFunc( void (*function)())
{
function();
}
int main(int argc, char* argv[])
{
// setup as the normalHi function
func=&normalHi;
func();
// change to the other function
func=&normalBye;
func();
// call the function pointed to within another function.
callFunc(func);
return 0;
}
Conclusion
Function pointers are very helpfully and you can setup a list a function pointers at run time which would not be know at compile time. Hopefully, this will help with better understanding of what a pointer and function pointers are.
I do really like to have any feedback regarding any tutorial/post, just reply or PM me.. glad to help, better to share knowledge.
This page was published on It was last revised on