home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
- From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
- Subject: Re: Pointer to member function as parameter
- Message-ID: <9224505.12975@mulga.cs.mu.OZ.AU>
- Keywords: pointer, member function
- Sender: news@cs.mu.OZ.AU
- Organization: Computer Science, University of Melbourne, Australia
- References: <Btv0xr.A6H@watcgl.uwaterloo.ca>
- Date: Mon, 31 Aug 1992 19:20:20 GMT
- Lines: 66
-
- bhickey@bambam.uwaterloo.ca (Bruce Hickey) writes:
-
- >Hi,
- >
- >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.
- [...]
-
- >#include <iostream.h>
- >
- >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?
- >}
-
- Try the following instead:
-
- // This function wants a pointer to a member function, and a pointer to
- // the object that we are going to call the member function for
- void freefunc( mine *object, double (mine::*f)(int) )
- {
- cerr << "calling func\n";
- (object->*f)(2); // 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
-
- Try one of the following here:
-
- freefunc(&test,&mine::func); // pass pointer to function (directly)
- freefunc(&test,pf); // pass pointer to function (via variable pf)
-
- >
- >}
- --
- Fergus Henderson fjh@munta.cs.mu.OZ.AU
- This .signature virus is a self-referential statement that is true - but
- you will only be able to consistently believe it if you copy it to your own
- .signature file!
-