Critical Section


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…

Home
Archive
'09
'08   '07   '06
'05   '04   '03
All Articles
Re:Cycling
Re:The Book
Re:Software
Re:Philosophy
About Me
W=UH
Email
Search

RSS   OPML

Greatest Hits
Correlation vs. Causality
The Tyranny of Email
Unnatural Selection
Lying
Aperio's Mission = Automating Pathology
On Blame
Try, or Try Not
Books and Wine
Google and Blogs
Emergent Properties
God and Beauty
Moving Mount Fuji The Nest Rock 'n Roll
IQ and Populations
Are You a Bright?
Adding Value
Confidence
The Joy of Craftsmanship
The Emperor's New Code
Toy Story
The Return of the King
Religion vs IQ
Most Spectacular Photos of 2003
In the Wet
the big day
solving bongard problems
visiting Titan
unintelligent design
Shorthorn
the nuclear option
second gear
On the Persistence of Bad Design...
Texas chili cookoff
the inflection point
almost famous design and stochastic debugging
may I take your order?
paper art
triple double
China's olympic gardens
New Yorker covers
Death Rider! (da da dum)
how did I get here (Mt.Whitney)?
the Law of Significance
Holiday Inn
Daniel Jacoby's photographs
room with a view
weird disaster update
in praise of paddle shifting
the first bird
Gödel Escher Bach: Birthday Cantatatata
shining a light
Father's Day (in pictures)
Tour de France 2009
Π