Path: utzoo!attcan!uunet!wuarchive!cs.utexas.edu!milano!cadillac!vaughan@mcc.com From: vaughan@mcc.com (Paul Vaughan) Newsgroups: comp.lang.c++ Subject: Re: Address of member function Message-ID: <12422@cadillac.CAD.MCC.COM> Date: 24 Oct 90 15:34:57 GMT References: <1392@carol.fwi.uva.nl> Sender: news@cadillac.CAD.MCC.COM Reply-To: vaughan@mcc.com (Paul Vaughan) Organization: MCC VLSI CAD Program Lines: 76 In-reply-to: delft@fwi.uva.nl (Andre van Delft) From: delft@fwi.uva.nl (Andre van Delft) For a call-back mechanism, I want to store the address of a non-static class member function. Turbo-C++ does not allow this ("member function pointers are not true pointer types, and do not refer to any particular instance of a class"). What does ANSI-C++ say about this? Are C++ implementations free to decide whether addresses of member functions are normal addresses? If so, what do other C++ implementations decide? Anyway, could ANSI-C++ be extended with a new kind of "access specifier" for a member function so that one can take the address of it? Both Cfront and g++ accept this usage of member functions class Foo { public: int foo() {} }; int (Foo::*f)() = Foo::foo; Foo aFoo; int bar = (aFoo.*f)(); However, pointers to member functions are not true pointer types in the sense that they occupy more storage than normal pointers--about three words worth. You will need to store or otherwise obtain the object that you intend to call the function on. Also note that storing pointers to member functions is not very flexible--you wouldn't be able to vary the arguments or the type of the object to call it on, for instance. I recommend an approach like this. class Foo { // a class that would want to post a callback public: void bar(int, float); }; Foo aFoo; class CallBack { // the base class for CallBacks public: virtual void operator()() = 0; }; class MyCallBack : public CallBack { // a callback class for Foo public: MyCallBack(Foo& f, int a1, float a2) : owner(f), arg1(a1), arg2(a2) {}; void operator()() { owner.bar(arg1, arg2); } private: Foo& owner; int arg1; float arg2; }; main() { CallBack& cb = *new MyCallBack(aFoo, 3, 3.141); // a posted callback cb(); // the invocation } If you then find that that you could use pointers to member functions in many cases (for instance, for functions declared on a certain base type that all took no arguments and returned void), you could create a special PMFCallBack class to avoid having to make a class definition for each sort of CallBack. Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan