home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.sys.sgi:11589 comp.lang.c++:11724
- Path: sparky!uunet!cs.utexas.edu!swrinde!mips!darwin.sura.net!uvaarpa!murdoch!virginia.edu!gs4t
- From: gs4t@virginia.edu (Gnanasekaran Swaminathan)
- Newsgroups: comp.sys.sgi,comp.lang.c++
- Subject: Re: C++ member pointer error
- Message-ID: <1992Jul29.154345.26476@murdoch.acc.Virginia.EDU>
- Date: 29 Jul 92 15:43:45 GMT
- References: <1992Jul28.184745.2854@babbage.ece.uc.edu>
- Sender: usenet@murdoch.acc.Virginia.EDU
- Reply-To: gs4t@virginia.edu (Gnanasekaran Swaminathan)
- Organization: University of Virginia
- Lines: 42
-
- tmcbraye@snert.ece.uc.edu (Tim McBrayer) wants to know how to
- use pointers to members of a class.
-
- Tim's example shortened and corrected.
-
- #include <iostream.h>
-
- class V{
- public:
- int i;
- V() { i = 0;};
- char * print(int x) {cout << "x is " << x << endl; return "Foo!";};
- };
-
- int main(){
- typedef char * (V::*fnptr)(int);
- fnptr fn = &V::print;
- V v;
- cout << (v.*fn)(5) << endl;
- }
-
- You need an object of a class to use a pointer to member of that
- class. In the above example, we used (v.*fn)(5) to call the function
- v.print(5). Similarly, other cases of pointers to members are used
- as follows:
-
- char* (V::*fptr)(int) = &V::print; // fptr is a pointer to member of V of type
- // char*(int)
- int V::*dptr = &V::i; // dptr is a pointer to member of V of type int
-
- V* vp;
- V v;
-
- vp->*dptr = 10; // set vp->i to 10
- v.*dptr = 11; // set v.i to 11
-
- (vp->*fptr)(10); // call vp->print(10)
- (v.*fptr)(11); // call v.print(11);
-
- Hope it helps someone.
-
- -Sekar
-