«

»

Mar 08

Pointing at Things That do Stuff!

Share

… that is, pointing at functions.

Introduction

Pointers in C++ are probably one of the most powerful aspects of programming using the language. They can allow you to easily pass data around with using additional memory and provide a very efficient way to access variables from elsewhere in the program.

But, that’s not all they can do. A very useful, yet not very often used, application of pointers is to be able to point to a function.

How Does it Work?

To be able to store a pointer to a function is relatively simple. You only need to know the return type and the parameters of the function you want to point to.

The format is roughly as follows.
[return-type] [*name_of_pointer][(parameter 1), (parameter 2), (...)];

Which is fairly simple. Here’s an example below.

#include <iostream>
using namespace std;
 
void OutputMessage( string text )
{
	cout << ">>>" << text << "<<<" << endl;
}
 
int main( int argc, char* argv[] )
{
	// Note: the brackets are important
	void (*output)(string text) = OutputMessage;
	output("Hello, world!");
 
	return 0;
}

As you can see, it’s not much more complicated than using a standard pointer. The brackets around the name of the variable and the asterisk are important, and it won’t work properly without them.

That Doesn’t Look Useful!

In the example given above, it doesn’t seem like a very useful thing to be able to do, after all if we can access the function, there’s no need for a pointer to it, right?

This gets useful when we pass the pointer to the function as a parameter in a function.

#include <iostream>
 
using namespace std;
 
void CallOutputFunction( void (*output)(string text) )
{
	output("Hello, world!");
}
 
void OutputMessage( string text )
{
	cout << ">>>" << text << "<<<" << endl;
}
 
int main( int argc, char* argv[] )
{
	CallOutputFunction( OutputMessage );
 
	return 0;
}

Now, again, in this example we could have accessed the function directly by name, but if you imagine instead that the CallOutputFunction function is instead a method within a class, it would be possible to effectively program something around a function that doesn’t yet exist, and then pass the function as a pointer.

That’s it really, have fun using pointers to functions!

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>