Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ncar!boulder!stan!garya From: garya@Solbourne.COM (Gary Aitken) Newsgroups: comp.lang.c++ Subject: pointer to virtual function; how to use it Keywords: virtual function pointer Message-ID: <856@garya.Solbourne.COM> Date: 21 Apr 89 22:29:33 GMT Organization: Solbourne Computer Inc., Longmont, Co. Lines: 98 Consider the following: class A : public { public: virtual void f() ; } ; class B::A : public { public: void f() ; } ; It is not unusual to need to take the address of a function, and pass it as an argument. The following possibilities arise: A *ap ; B *bp ; A *objp ; void (*fp)() ; ap = new A ; bp = new B ; objp = (A*) bp ; 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 The intent is to get the pointer to the proper function via the virtual table. This does, in fact, work with cfront, although you get a warning telling you to use :: (which won't compile, since it expects a class name in front of it instead of a pointer to a class object). 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? The only way I know to do it is by using straight C code, relying on the fact that cfront passes "this" as the first argument. But what about other implementations? Example of what works in cfront: // void dispatch(A *ap, void (*A::fp)()) How would one write this??? void dispatch(A *ap, void (*fp)(A*)) { // ap->(*fp)() ; // This is what I really want... (*fp)(ap) ; // This is what works return ; } Can anyone help me out on this (ooooooo is that a pun?) ? Here's a complete program to play with: ============================= Cut Here ================================ void printf(...) ; class A { public: virtual void f() ; } ; void A::f() {printf("A.f\n");} class B : public A { public: void f() ; } ; void B::f() {printf("B.f\n");} //void dispatch(A *ap, void (*A::fp)()) void dispatch(A *ap, void (*fp)(A*)) { // ap->(*fp)() ; /* how do we do this???? */ (*fp)(ap) ; /* this works for cfront, but what about others?? */ return ; } main() { A *ap ; B *bp ; A *objp ; auto void (*fp)() ; ap = new A ; bp = new B ; objp = (A*) bp ; 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 function // dispatch(objp, (void (*)()) fp) ; dispatch(objp, (void (*)(A*)) fp) ; } -- Gary Aitken Solbourne Computer Inc. ARPA: garya@Solbourne.COM Longmont, CO UUCP: ...!{boulder,sun}!stan!garya