home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!sun-barr!cs.utexas.edu!devnull!thunder.Berkeley.EDU!rjf
- From: rjf@thunder.Berkeley.EDU (Russell Fleming)
- Newsgroups: comp.lang.c++
- Subject: Re: Pointer to member function as parameter
- Keywords: pointer, member function
- Message-ID: <2366@devnull.mpd.tandem.com>
- Date: 2 Sep 92 19:05:41 GMT
- References: <Btv0xr.A6H@watcgl.uwaterloo.ca>
- Sender: news@devnull.mpd.tandem.com
- Lines: 96
-
- In article <Btv0xr.A6H@watcgl.uwaterloo.ca>, bhickey@bambam.uwaterloo.ca
- (Bruce Hickey) writes:
- >
- > I am attempting to pass a pointer to a member function as an argument to
- > a function. Neither Stroustrup (2nd Ed) or Lippman (2nd Ed) cover this
- > subject directly, to my knowledge.
- >
- > I am trying to create a pointer to a member function as well as use that
- > pointer to call the function. The problem arises when I try to pass this
- > pointer as a paramter to a function. There appears to be no reason why this
- > is not possible.
- >
- > class mine {
- > public:
- > double func( int );
- > };
- >
- > double mine::func( int var1 )
- > {
- > cerr << var1 << "\n";
- > return 0.1;
- > }
- >
- > // This function wants a pointer to a member function.
- > void freefunc( double (mine::*f)(int) )
- > {
- > cerr << "calling func\n";
- > (*f)(2); // How do I call the function?
- > }
- >
- > int main()
- > {
- > mine test;
- >
- > double (mine::*pf)(int) = &mine::func;
- >
- > (test.*pf)(5); // Call the member function through pointer
- >
- > freefunc(test.*pf); // Attempt to pass pointer to function
- >
- > }
- >
-
- There is nothing wrong with your declaration of a pointer to the member
- function. The problem lies with your use of the pointer. All
- non-static member functions have an implied "this" argument which is
- used to access the data associated with the object. When you use a
- ptr-to-mem-fcn to invoke the function, you must also provide the object
- which the function is to act upon (ie. (this->*f)(2)). Two solutions to
- your problem are available. The first elimintates the need for a
- pointer. Simply modify your code as follows:
-
- void freefunc (mine& m)
- {
- cerr << "calling func\n";
- m.func (2);
- }
-
- int main ()
- {
- mine test;
- freefunc (test);
- }
-
- Alternatively, since the member function you are using does not (as
- shown) rely on any data from the object,
- you could re-write your code to use a pointer function as follows:
-
- class mine {
- public:
- static double func(int);
- };
-
- double mine::func (int var1)
- {
- cerr << var1 << "\n";
- return 0.1;
- }
-
- void freefunc (double (*f)(int))
- {
- cerr << "calling func\n";
- (*f)(2);
- }
-
- int main ()
- {
- mine test;
- double (*pf)(int) = &mine::func;
- freefunc (pf);
- }
-
- =================================================================
- Rusty Fleming, Software Consultant @ Tandem Computers Inc.
- email: rjf@mpd.tandem.com Austin, Texas
- voice: (512) 244 - 8390 USA
-