[lug] (OT) C++ ?, pointers to member functions

D. Stimits stimits at idcomm.com
Tue Aug 7 16:20:28 MDT 2001


"Scott A. Herod" wrote:
> 
> This is off topic but there are a lot of experts here.
> 
> How can I pass a pointer to a non-static member function?
> 
> I've got a static sample below but really want b::fp to be
> non-static.  Must I use a static, have it reference a non-static
> and pass around a 'this' pointer?

For that to work, it needs to be a virtual function. And in the case of
a virtual function, you need to use it only as a relative offset, from
the object itself. If you have the paperback Stroustrup book, 3rd
edition, see section 15.5, pages 418 through 420. When the function
becomes virtual, the vtable offset is like a blueprint that will remain
consistent even across memory spaces, so you could even use this to
point to member functions of an object from a dynamic library that is
mapped to some other memory space (the "shape of the offset" will remain
constant).

D. Stimits, stimits at idcomm.com

> 
> Thanks,
> 
> Scott
> 
> ==============================================================
> #include <iostream>
> 
> typedef void (fpLOCK_WRITE)();
> 
> class f_ptr
> {
> public:
>     f_ptr( fpLOCK_WRITE* t ) { writer = t; }
>     void write() { writer(); }
> private:
>     fpLOCK_WRITE* writer;
> };
> 
> class b {
> public:
>     static void fp() { cout << "Hello World!" << endl; }
> };
> 
> int main( int argc, char* argv[] )
> {
>     b* bp = new b();
>     f_ptr* f = new f_ptr( b::fp );
> 
>     f->write();
>     return( 0 );
> }
> _______________________________________________
> Web Page:  http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug



More information about the LUG mailing list