C++: Pointers to member functions

Now, C++ programmers can all program C, to varying degrees of competency. And some know that in C you can store an entire function in a pointer, like so:

int DoTheThingThisWay(double count)
{
...
}

int DoTheThingThatWay(double count)
{
...
}

int (*DoTheThing)( double );  // define the variable
DoTheThing = &DoTheThingThatWay; // set the variable
result = DoTheThing( 2.0 );  // call the function, whatever it is now

Giving you a nifty kinda polymorphism. People who have programmed in C, and needed something like this (say for a state machine) have gone “neat!” and remembered it for later.

So, here we are, later. I’m working in C++ and going to do a state machine. Objects and all. I recall that you can do that polymorphic thing with function pointers, and quickly reconstruct the syntax. Now, with objects I want to point at a function on an object rather than a dumb, lying around knowing nothing about objects function. Easy, let’s just whip that up, I’ve proven how pretty the syntax for calling an arbitary function is, now just to call an arbitary member function.

Half an hour of wrestling with the compiler later, an observation is made along the lines of “everyone does this, just look it up on the web”. Top hit on a Google search for C++ “member function” pointer is http://www.goingware.com/tips/member-pointers.html – which is the right page, and you end up with the call:

result = (objectInstance.*DoTheThing)( 2.0 );

which ain’t so pretty. But you need to do that to provide the hidden this pointer, because you’re working with member functions here, not boring old functions. Add some parameters, store the pointers in an array and before you know it you’ve got

result = (objectInstance.*DoTheThing[FunctionIndex])( 2.0, InitalStringSize, HuffalumpFactor );

which is a long way from DoTheThing(2.0), and I’m not sure what you just got for all that effort. Certainly not readability. Try a pointer to a polymorphic type instead (maybe even a functiod?), and flip the pointer to different objects as you go. Much nicer:

class CThingDoer
{
public:
	virtual int operator(double count);
...
};

class CDoTheThingThisWay : public CThingDoer
{
public:
	virtual int operator(double count);
...
} DoTheThingThisWay

class CDoTheThingThatWay : public CThingDoer
{
public:
	virtual int operator(double count);
...
} DoTheThingThatWay

CThingDoer* DoTheThing;  // define the variable
DoTheThing = &DoTheThingThatWay; // set the variable
result = DoTheThing( 2.0 );  // call the function, whatever it is now