If you have a struct like this one
struct A {
void func();
};
and a reference like this one
A& a;
you can get a pointer to its func
method like this:
someMethod(&A::func);
Now what if that method is virtual and you don't know what it is at run-time? Why can't you get a pointer like this?
someMethod(&a.func);
Is it possible to get a pointer to that method?
You can get a pointer to it, like so:
The way to invoke a function pointer is to also provide its object's instance pointer. This will take care of all virtuality issues:
OK, interesting
syntax challengequestion: Suppose I have this.Now if I have
Derrek * p
or aBasil * p
, I can invoke theBasil
member viap->Basil::foo()
. How could I do the same if I was given avoid(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!]Pointers to members take into account the virtuality of the functions they point at. For example:
Outputs: