Sorry for the double-answer, but seeing the original post makes it a lot more clear what you're looking for, and it's a related but kind of different use of function pointers. What you have there is a callback.
Let's say you want a function to download a file from the Internet. So you write:
void DownloadFile(std::string URL, std::string discLocation);
Now, that's great, right up until you try to download a very large file. Suddenly DownloadFile
is taking a long time to finish, and you don't know how long it'll be. Boy, things would be a lot easier if you only had a progress indicator of some sort to let you know how far along you are! But DownloadFile
can't return until it's finished, and you don't want to teach DownloadFile
itself about your progress indicator, because that would lead to high coupling and make it harder to reuse DownloadFile
in another context.
What you can do instead is give it a callback, a function pointer that DownloadFile
uses to call you back after you call it. In fact, you'd probably want two:
void DownloadFile(std::string URL, std::string discLocation,
intFunction FileSize, intFunction FileProgress);
(Where intFunction
is a function pointer that takes one int as an argument.) It would call FileSize
once to set the size of the file, and FileProgress
repeatedly to inform you of how far along it is in the download. With these two pieces of information available, you can wire up a progress bar or some other type of progress indicator, without having to couple DownloadFile
directly to the progress bar control.
That's the sort of power that callbacks make available. You see them a lot in code that deals with long-running events. Downloads, for example, or code for playing sound and music. In a music callback, you can perform custom edits to the sound as it's being played to add effects, or read the sound buffer and display a representation of it on an equalizer.