The way to invoke a function pointer is to also provide its object's instance pointer. This will take care of all virtuality issues:
struct A { void func(); };
int main()
{
typedef void (A::*mf)();
A x; // irrelevant if A is derived or if func is virtual
mf f = &A::func; // pointer-to-member-function
A* p = &x; // pointer-to-instance
(p->*f)(); // invoke via pointer
(x.*f)(); // invoke directly
}
OK, interesting syntax challenge question: Suppose I have this.
struct Basil { virtual void foo(); virtual ~Basil(); };
struct Derrek : public Basil { virtual void foo(); };
Now if I have Derrek * p
or a Basil * p
, I can invoke the Basil
member via p->Basil::foo()
. How could I do the same if I was given a void(Derrek::*q)() = &Derrek::foo
?
Answer: It cannot be done. The PMF q
alone does not know whether it points to a virtual function, let alone which one, and it cannot be used to look up a base class function at runtime. [Thanks to Steve and Luc!]