Programming Page

last updated 15th Nov 2002

C/C++

1. Pointers to member functions

The syntax is as follows:

// Define a typedef called pf3 that improves readability later on. Assume CBase has a public member function called Func_NotInherited(int&, unsigned char) that returns an unsigned long
typedef unsigned long (CBase::*pf3)(int&, unsigned char);

void func()
{

CBase Base;// This is just for convenience, it's the pointer we actually want
CBase* pBase = &Base;
int i=8;
unsigned char a = 32;

// Define a variable called pFNI of type pf3 that points to a member function of the class CBase. Note our function pointer "pFNI" is only an offset into the classes V-table that is useless until we tell it which instance to actually dereference.
pf3 pFNI = &CBase::Func_NotInherited;

// Now tell our variable which instance of CBase it's to (de)reference when we call MyFunc_NotInherited
unsigned long res = (pBase->*pFNI)(i,a);
}