home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!cs.utexas.edu!torn!watserv2.uwaterloo.ca!watmath!watcgl!bambam.uwaterloo.ca!bhickey
- From: bhickey@bambam.uwaterloo.ca (Bruce Hickey)
- Subject: Pointer to member function as parameter
- Message-ID: <Btv0xr.A6H@watcgl.uwaterloo.ca>
- Keywords: pointer, member function
- Sender: news@watcgl.uwaterloo.ca (USENET News System)
- Organization: Computer Graphics Laboratory, University of Waterloo, Ontario, Canada
- Date: Mon, 31 Aug 1992 18:05:51 GMT
- Lines: 86
-
- 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.
-
- Compiling the attached code I get two errors:
-
- 1) "test.cc", line 17: error: object missing in call through pointer to member function - If this is incorrect how would I call the function?
-
- 2) "test.cc", line 28: error: & .* expression - Since I want to pass a pointer
- do I not need its address?
-
- The second piece of code, which works, uses only global functions. The
- extension of this code to include class member functions is unpleasantly
- confusing.
-
- Suggestions regarding the solutions or simply a correct example would be
- appreciated.
-
- Thanks,
- Bruce Hickey
-
- -------------------- Compiled with AT&T 3.0.1 ------------------------------
- #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?
- }
-
- 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
-
- }
-
- -----------------------Working version with only global functions ------------
-
- #include <iostream.h>
-
- double func1( int var)
- {
- cerr << "func 1 " << var << "\n";
- return 0.1;
- }
-
- void freefunc1( double (*f)(int) )
- {
- cerr << "calling func1\n";
- f(2);
- }
-
- int main()
- {
- double (*pf1)(int) = func1;
-
- (*pf1)(5); // Call the function through the pointer
- freefunc1(*pf1); // Pass the pointer to the fuction as a parameter
-
- }
-
-