Friday, June 09, 2006

C++ class member function pointers

This prints -7:


#include <stdio.h>

struct Moo
{
int func () const { return -value; }
int value;
};

int main ()
{
Moo m; m.value = 7;

int (Moo::*funcPtr) () const = &Moo::func;
printf ("%d\n", (m.*funcPtr) ());
return 0;
}


Gotta love the "int (Moo::*) ()" syntax - pointer to any member function of class "Moo" as long as it returns an "int" an accepts nothing.

And of course, "(m.*funcPtr) ()", which invokes the pointed-to function with "m" as "this".

1 comment:

Known said...

You will learn more from http://www.newty.de/fpt/index.html