Sunday, May 18, 2008

Pointers to Methods in C++

Working through the ECMA script (JavaScript) interpreter I had some problems compiling a dispatch table that used function pointers. The function pointers were to non-static object methods. My gut reaction was that this must be wrong and a non-standard MSDN/Visual C++ extension. Having worked with C++ for a long time you sort of assume that you know the beast.

I briefly started converting the methods to static methods that passed in the object this in as the first parameter before I stepped back and looked at the problem properly. Function pointers to class methods are a part of the C++ standard. It required a very light touch to get the code to compile correctly. Here is a stolen code sample illustrating pointers to methods. I have modified it slightly to include a typedef for the method pointer.

class Adder
{
int x;
public:
Adder(int in) : x(in) { }
int addx(int y) { return x + y; }

// declare MethodPointer
typedef int (Adder::*MethodPointer)(int);
};

int main()
{
// pointer to the addx method
Adder::MethodPointer new_function
= &Adder::addx;

// Create an Adder instance
Adder foo = Adder(3);

// Call the method
std::cout << (foo.*new_function)(5)
<< std::endl; // prints "8"
return 0;
}
As ever I stand back staggered by what is out there on the internet. Wikipedia has an excellent section on function pointers here - and amazingly there is/was a site http://www.function-pointer.org/ dedicated to explanations of function pointers.

No comments: