Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!sun-barr!newstop!exodus!morocco.Eng.Sun.COM!landauer From: landauer@morocco.Eng.Sun.COM (Doug Landauer) Newsgroups: comp.lang.c++ Subject: Re: Pointers to functions anyone? Summary: Ptr-to-member-function is NOT just ptr-to-function Keywords: pointer-to-functions inside class Message-ID: <1069@exodus.Eng.Sun.COM> Date: 30 Sep 90 00:40:37 GMT References: <6472@wolfen.cc.uow.oz> Sender: news@exodus.Eng.Sun.COM Distribution: comp Organization: Sun Microsystems, Mt. View, Ca. Lines: 70 > Please email replies - I'll summarise here if someone has a solution! I tried to, but I got an error message back <<< 554 ... Unknown domain : cc . uow . oz 554 ... Service unavailable So, this time I'll just post it. > I'm trying to set up an array of pointers to functions within a class, > much like the example here (for simplicity no array here): > > #include > > class test { > void f1(int i) // function to be called > { cout<<"ok"< > void (test::*ptf)(int); // pointer-to-function Whoops, your comment shows what's missing here. ptf is *not* a "pointer-to-function". Instead, it is a "pointer-to-MEMBER-function", which is a different beast altogether. > > public: > test() { ptf=test::f1; } // constructor - assigns &f1 to ptf > void execute (int i) > { (*ptf)(i); } // try to call f1() > }; > > main() { > test variable; > variable.execute(1); > } > > My compiler (Turbo C++ V1.0) complains about the call (*ptf)(i): > > -- Temporary used for parameter 'this' in function test::execute(int) > -- Type mismatch in parameter 'this' in function test::execute(int) > -- Parameter 'i' is never used in function test::execute(int) cfront 2.1 shows a little more clearly what's happening: "bernt.cc", line XX: error: pointer to member dereferenced Read the E&S ARM section about pointers to members, and your compiler should be much happier about compiling your code. In order to make your little test acceptable to cfront, all I had to do was change the call to give the ptr-to-member-fn an explicit "this" for which to call the function that it pointed at. Like so: Change the line > { (*ptf)(i); } // try to call f1() to a line like > { (this->*ptf)(i); } // try to call f1() > What am I doing wrong?? All pointers-to-members must be given an object for which to call their pointed-at functions. Even if the call is from within another member function. Ptrs-to-members are usually implemented as OFFSETs within the class, rather than as true pointers. I hope this helps.... -- Doug Landauer - Sun Microsystems, Inc. - Languages - landauer@eng.sun.com Matt Groening on C++: "Our language is one great salad."