<<< (new yorker, 6/13/04)

Home

Resurfacing >>>


C++ method pointers

Thursday,  06/17/04  08:57 AM

Have you ever wanted to use a pointer to a class method?  This might be basic C++ but I couldn’t remember how to do it, and spent some time Googling and messing around to figure it out.  So here’s the way:


To define a pointer to a class method:


returnval (myclass::*method)(parameters…)


For example:


char *(myclass::*pmethod)(int parm);


This defines a pointer named pmethod to a method of the myclass class.  The method has a single int parameter and returns a char*.


To assign a value to the pointer:


pmethod = &myclass::method;


For example:


pmethod = &myclass::mymethod;


This sets pmethod to point to mymethod.


To call the class method:


(myobject.*method)(parameters…)


For example:


mychar = (myobject.*pmethod)(myint);


This calls the method pointed to by pmethod.


The pointer can itself be in a struct or class as well.  For example:


struct {                      // processing table

char  *name;

char  *(myclass::*pmethod)(int parm);

} proctbl[] = {

{ “text”,  &myclass::mymethod},

{ “text2”,&myclass::anothermethod}

};


This defines a table of structures with two entries, each of which has a method pointer.  The function can then be called as follows:


mychar = (myobject.*proctbl[index].pmethod)(myint);


In this example, the pointer proctbl[index].pmethod identifies the method to be called.


Note that “::*” and “.*” are actually separate operators in C++.  There is also a “->*” operator.


You might never need this, but just in case you do…