Function Pointer Examples

Started by
6 comments, last by rip-off 17 years, 7 months ago
Hey there, Recently I'm starting to regret a lazy/bad decision I made earlier when I started to study C++ programming. I thought to myself, I'm not going to be programming large programs for a long time; I'm not going to be doing projects with linking source code files, or operating system/networking programming. Well now I am in the position were I have come back to the subject of learning pointers and how useful they really are. I've grabbed the basic concept of how simply changing the pointer affects the variable it’s pointing to (variable memory address). Now the reason why I'm asking this question, although I'm sure there have been many similar questions like this before but with less detail in reference to mine, as I could not find anything directly related to the topic through searching. My question is actually more of request, would someone be able to give me a sample code and explanation of a situation in which you'd want to/need to use function pointers. It’s the only question I find I'm still asking myself, which is holding me back from moving on to using pointers and arrays. I appreciate any time spent in reading and responding to my topic, -PB
Advertisement
Callback mechanisms is common to implement using function pointers. This page seems to give a good overview.
[s]--------------------------------------------------------[/s]chromecode.com - software with source code
Hope this helps you out with pointers. [smile]

Also, you want to use pointers when u want to be able to display a variable or do something with it, without having to copy the object to the function. Saves you overhead.

// Brandon Wall : 8/5/06// Understanding the concept of pointers and functions#include <string>#include <iostream>using namespace std;int getNum(string question);int calc(const int* const pValue1, const int* const pValue2, int total);int main(){	int total = 0;	int num1 = getNum("Enter in a number: ");	int num2 = getNum("Enter in a number: ");	int Total = calc(&num1,&num2,total);	cout << "\nThe total = " << Total << "\n\n";	return 0;}int getNum(string question){	int num = 0;	cout << question;	cin >> num;	return num;}int calc(const int* const pValue1, const int* const pValue2, int total){	total = *pValue1 + *pValue2;	return total;}
Thanks a lot Enselic and Nuclear Rabbit, I've found this page before but found the concept in my book somewhat easier to understand, but I will make sure to use the linked page as reference to help clear up future questions. I also want to say thanks to Nuclear Rabbit for the code example and the heads up on the additional use for pointers and variables.

-PB
Quote:Original post by NUCLEAR RABBIT
Hope this helps you out with pointers. [smile]

Also, you want to use pointers when u want to be able to display a variable or do something with it, without having to copy the object to the function. Saves you overhead.

*** Source Snippet Removed ***
A couple of comments on your example (for the benefit of the OP):

1) For built-in or other types whose size is only a few bytes, passing by pointer rather than value doesn't gain you much (if anything) in the way of efficiency. Your calc() function should just be pass-by-value. Also, there's no need for the 'total' argument; it can simply be a variable local to calc(), or you can just implement calc() as 'return *pValue1 + *pValue2;'

2) For larger objects, in C++ it's more idiomatic to use references rather than pointers. Among other things, this simplifies debugging and can avoid common errors (remember, references cannot be null and are not reassignable).

3) Ironically, the one place where you should be passing by reference or pointer, you're not :) The getNum() function as currently implemented must make a copy of the string argument, which actually can incur some overhead. It should instead by passed by constant reference.
I once made a long long post about function pointers and some of their caveats. Let me fetch the link...

Ah, here it is:
http://www.gamedev.net/community/forums/viewreply.asp?ID=2718503
.:<<-v0d[KA]->>:.
Function pointers in C++? no problem.
First, the general syntax for declaring a function pointer value and assigning it a value.

int Funct(int);

above is a function header, typical, that takes an int value and returns an int value.
Here is a function pointer declaration with the name 'lpFunction', that takes an int as a parameter and returns a value of type int.

int (*lpFunction)(int);

the syntax is a little complicated, but you can drop this pretty much anywhere just like you would a normal variable, but the syntax can get pretty messy. To assign it a value, you'd do something like this.

lpFunction = Funct;

now when you use this line, lpFunction points to Function, as declared above. It's worth noting that the return value type and the parameter listing must match. To call the function, you'd do somethine like this.

int val = lpFunction(5);
// is the same as int val = Funct(f);

This calls the function lpFunction is pointing to, which in this case is Funct, with the parameter 5, and returns Funct's return value, assigning it to val. Obviously you don't HAVE to assign the return value to anything, but in this case i did.

You can also pass function pointers as parameters to other functions, and return function pointers as parameters to other functions. Here is how you'd set up a function header to accept a parameter that is a function pointer.

int Something(int (*lpFunction)(int));

this function takes a pointer to a function, and returns an int. The function that it takes a pointer to, must be of a type to accept an int value as a parameter, and returns an int value.

To call the above function, you'd do this [to use the above examples].

int val2 = Something(Funct); // calls Something, using the function Funct.

or

int val2 = Something(lpFunction); // since lpFunction is of the correct type, and points to Funct at the moment, these two examples are the same.

The syntax gets pretty ugly and messy though when you attempt to return a function pointer from another function, which is why I'm covering this last. To return a function pointer, that takes an int as a parameter and returns an int, from a function that takes a char for a parameter [just different to show where the parameter lists change], the header would look like this

int (*ReturnsAFunctionPointer(char))(int);

ugly. But powerful! You'd use it like this

lpFunction = ReturnsAFunctionPointer('a');

Obviously this is very powerful, and is the method that a lot of scripting languages use to 'expose' C/C++ functions to a script. This is also the way that 'virtual functions' were handled before C++ came along. This is how C did a similar thing, before the compiler took care of all of that for you. Obviously it's a lot cleaner to use virtual functions now than function pointers, but function pointers are still very useful.

*edit* sorry it's so long, but its a complicated subject. Looks like i was beaten to it too. : /
For you own sake use typedefs when working with function pointers.

int someFunction( int , float );typedef int (*SomeFunctionPointer)( int, float );SomeFunctionPointer = &someFunction;int functionThatTakesAFunctionPointer( SomeFunctionPointer func );

This topic is closed to new replies.

Advertisement