home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / cplus / 13108 < prev    next >
Encoding:
Text File  |  1992-08-31  |  2.2 KB  |  79 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
  3. From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
  4. Subject: Re: Pointer to member function as parameter
  5. Message-ID: <9224505.12975@mulga.cs.mu.OZ.AU>
  6. Keywords: pointer, member function
  7. Sender: news@cs.mu.OZ.AU
  8. Organization: Computer Science, University of Melbourne, Australia
  9. References: <Btv0xr.A6H@watcgl.uwaterloo.ca>
  10. Date: Mon, 31 Aug 1992 19:20:20 GMT
  11. Lines: 66
  12.  
  13. bhickey@bambam.uwaterloo.ca (Bruce Hickey) writes:
  14.  
  15. >Hi,
  16. >
  17. >I am attempting to pass a pointer to a member function as an argument to
  18. >a function. Neither Stroustrup (2nd Ed) or Lippman (2nd Ed) cover this
  19. >subject directly, to my knowledge. 
  20. >
  21. >I am trying to create a pointer to a member function as well as use that 
  22. >pointer to call the function. The problem arises when I try to pass this 
  23. >pointer as a paramter to a function. There appears to be no reason why this 
  24. >is not possible. 
  25. [...]
  26.  
  27. >#include <iostream.h>
  28. >
  29. >class mine {
  30. >public:
  31. >    double func( int );
  32. >};
  33. >
  34. >double mine::func( int var1 ) 
  35. >{ 
  36. >    cerr << var1 << "\n"; 
  37. >    return 0.1;
  38. >}
  39. >
  40. >// This function wants a pointer to a member function.
  41. >void freefunc( double (mine::*f)(int) ) 
  42. >{ 
  43. >    cerr << "calling func\n";
  44. >    (*f)(2);            // How do I call the function?
  45. >}
  46.  
  47. Try the following instead:
  48.  
  49. // This function wants a pointer to a member function, and a pointer to
  50. // the object that we are going to call the member function for
  51. void freefunc( mine *object, double (mine::*f)(int) ) 
  52.     cerr << "calling func\n";
  53.     (object->*f)(2);            // call the function
  54. }
  55.  
  56. >int main()
  57. >{
  58. >mine test;        
  59. >
  60. >double (mine::*pf)(int) = &mine::func;
  61. >
  62. >(test.*pf)(5);         // Call the member function through pointer
  63. >
  64. >freefunc(test.*pf);     // Attempt to pass pointer to function
  65.  
  66. Try one of the following here:
  67.  
  68. freefunc(&test,&mine::func);     // pass pointer to function (directly)
  69. freefunc(&test,pf);         // pass pointer to function (via variable pf)
  70.  
  71. >
  72. >}
  73. -- 
  74. Fergus Henderson             fjh@munta.cs.mu.OZ.AU      
  75. This .signature virus is a self-referential statement that is true - but 
  76. you will only be able to consistently believe it if you copy it to your own
  77. .signature file!
  78.