home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / sys / sgi / 11589 < prev    next >
Encoding:
Text File  |  1992-07-29  |  1.5 KB  |  56 lines

  1. Xref: sparky comp.sys.sgi:11589 comp.lang.c++:11724
  2. Path: sparky!uunet!cs.utexas.edu!swrinde!mips!darwin.sura.net!uvaarpa!murdoch!virginia.edu!gs4t
  3. From: gs4t@virginia.edu (Gnanasekaran Swaminathan)
  4. Newsgroups: comp.sys.sgi,comp.lang.c++
  5. Subject: Re: C++ member pointer error
  6. Message-ID: <1992Jul29.154345.26476@murdoch.acc.Virginia.EDU>
  7. Date: 29 Jul 92 15:43:45 GMT
  8. References: <1992Jul28.184745.2854@babbage.ece.uc.edu>
  9. Sender: usenet@murdoch.acc.Virginia.EDU
  10. Reply-To: gs4t@virginia.edu (Gnanasekaran Swaminathan)
  11. Organization: University of Virginia
  12. Lines: 42
  13.  
  14. tmcbraye@snert.ece.uc.edu (Tim McBrayer) wants to know how to
  15. use pointers to members of a class.
  16.  
  17. Tim's example shortened and corrected. 
  18.  
  19. #include <iostream.h>
  20.  
  21. class V{
  22. public:
  23.   int i;
  24.   V() { i = 0;};
  25.   char * print(int x) {cout << "x is " << x << endl; return "Foo!";};
  26. };
  27.  
  28. int main(){
  29.   typedef char * (V::*fnptr)(int);
  30.   fnptr fn = &V::print;
  31.   V v;
  32.   cout << (v.*fn)(5) << endl;
  33. }
  34.  
  35. You need an object of a class to use a pointer to member of that
  36. class. In the above example, we used (v.*fn)(5) to call the function
  37. v.print(5). Similarly, other cases of pointers to members are used
  38. as follows:
  39.  
  40. char* (V::*fptr)(int) = &V::print; // fptr is a pointer to member of V of type
  41.                    // char*(int)
  42. int   V::*dptr = &V::i; // dptr is a pointer to member of V of type int
  43.  
  44. V* vp;
  45. V  v;
  46.  
  47. vp->*dptr = 10; // set vp->i to 10
  48. v.*dptr   = 11; // set v.i to 11
  49.  
  50. (vp->*fptr)(10); // call vp->print(10)
  51. (v.*fptr)(11);   // call v.print(11);
  52.  
  53. Hope it helps someone.
  54.  
  55. -Sekar
  56.