Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!bionet!agate!saturn!saturn.ucsc.edu!daniel From: daniel@saturn.ucsc.edu (Daniel Edelson) Newsgroups: comp.lang.c++ Subject: Does ptr to func always work? Keywords: point to function, pointer to member Message-ID: <6364@saturn.ucsc.edu> Date: 14 Feb 89 23:36:52 GMT Sender: daniel@saturn.ucsc.edu Reply-To: daniel@saturn.ucsc.edu (Daniel Edelson) Organization: University of California, Santa Cruz; CIS Lines: 67 Can somebody please enlighten me as to why this does not work. It declares a member that points to a member function. The constructor initializes the pointer based on an argument. When calling through the pointer to function the argument gets lost. This can be fixed with pointers to member but I'd like to understand why it doesn't work as simple pointers to functions. We've tried this under cfront 1.2.1 and under oregon C++. #include typedef void (*ptr_f)(int); // simple pointer to func type class FUNC { public: ptr_f pF; void F1(int i) { cout << "F1: " << i << "\n"; } void F2(int i) { cout << "F2: " << i << "\n"; } FUNC(int i) { if (i==0) pF= (ptr_f) &(FUNC::F1); // point at F1 else pF= (ptr_f) &(FUNC::F2); // point at F2 } }; main() { FUNC Q(1); // Select F2 Q.F1(10000); // invoke F1 directly Q.F2(10000); // invoke F2 directly (Q.pF)(10000); // invoke F2 indirectly, 10000 gets lost } A solution using pointers to member is: #include class FUNC ; // forward decl typedef void (FUNC::*ptr_mf)(int); // pointer to member type class FUNC { public: ptr_mf pF; void F1(int i) { cout << "F1: " << i << "\n"; } void F2(int i) { cout << "F2: " << i << "\n"; } FUNC(int i) { if(i==0) pF= &(FUNC::F1); else pF= &(FUNC::F2); } }; main() { FUNC Q(1); Q.F1(10000); Q.F2(10000); (Q.*(Q.pF))(10000); //Yuck! } =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Daniel Edelson daniel@saturn.ucsc.edu