Critical Section

Archive: June 17, 2004

<<< June 16, 2004

Home

October 15, 2004 >>>


(new yorker, 6/13/04)

Thursday,  06/17/04  01:07 AM

complaints

 

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…

 
 

Return to the archive.

Home
Archive
'13   '12   '11
'10   '09   '08
'07   '06   '05
'04   '03   all
About Me
W=UH
Email
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
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
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
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
in praise of paddle shifting
the first bird
Gödel Escher Bach: Birthday Cantatatata
shining a light
Father's Day (in pictures)
your cat for my car
discovering the third quadrant
Jobsnotes of note
world population map
no joy in Baker
introducing eyesFinder