Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!indri!unmvax!tut.cis.ohio-state.edu!rutgers!att!ulysses!andante!alice!shopiro From: shopiro@alice.UUCP (Jonathan Shopiro) Newsgroups: comp.lang.c++ Subject: Re: pointer to virtual function; how to use it Summary: Use pointers to members Keywords: virtual function pointer Message-ID: <9228@alice.UUCP> Date: 22 Apr 89 22:53:41 GMT References: <856@garya.Solbourne.COM> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 62 In article <856@garya.Solbourne.COM>, garya@Solbourne.COM (Gary Aitken) writes: (with condensation and a few syntax errors fixed) > > Consider the following: > > class A { > public: > virtual void f() ; void g(); // not virtual > } ; > > class B : public A { > public: > void f() ; void g(); // not virtual > } ; > > A* ap = new A; > B* bp = new B; > A* objp = bp; // no cast necessary > > It is not unusual to need to take the address of a function, and pass it > as an argument. The following possibilities arise: > > fp = &A::f ; // static reference to a known function > fp = &B::f ; // static reference to a known function > fp = &objp->f ; // dynamic ref to unknown (at compile time) virtual funct For virtual functions, only dynamic (time of call) binding is supported. Do it this way: typedef void A::MEMF(); // MEMF is the type of a member function of A MEMF* fp = &A::f; (There is a way to do it without a typedef, but this is easier). Then the calls go like this: (ap->*fp)() // A::f() (bp->*fp)() // B::f() (objp->*fp)() // B::f() fp = &A::g; // note the variable can refer // to a virtual or non-virtual function (ap->*fp)() // A::g() (bp->*fp)() // A::g() (objp->*fp)() // A::g() There is no way to apply A::f() to a B object (but you're not supposed to want to :-)). > Now consider a function which has been passed two arguments, one a pointer > to an object, and the other a pointer to a member function for that object. > How do you invoke the member function? void dispatch(A *ap, MEMF* fp) // this is how { (ap->*fp)(); // This is what I really want... // you got it } -- Jonathan Shopiro AT&T Bell Laboratories, Warren, NJ 07060-0908 research!shopiro (201) 580-4229