Contents Up << >>

How do I declare an array of pointers to member functions?

Keep your sanity with "typedef".

  	class Fred {
	public:
	  int f(char x, float y);
	  int g(char x, float y);
	  int h(char x, float y);
	  int i(char x, float y);
	  //...
	};

	typedef  int (Fred::*FredPtr)(char x, float y);
Here's the array of pointers to member functions:

  	FredPtr a[4] = { &Fred::f, &Fred::g, &Fred::h, &Fred::i };
To call one of the member functions on object "fred":

  	void userCode(Fred& fred, int methodNum, char x, float y)
	{
	  //assume "methodNum" is between 0 and 3 inclusive
	  (fred.*a[methodNum])(x, y);
	}
You can make the call somewhat clearer using a #define:

  	#define  callMethod(object,ptrToMethod) ((object).*(ptrToMethod))
	callMethod(fred, a[methodNum]) (x, y);
  • Container classes and templates