In C++, can member function pointers be used to point to derived (or even base) class members?
EDIT:
Perhaps an example will help. Suppose we have a hierarchy of three classes X, Y, Z in order of inheritance.
Y therefore has a base class X and a derived class Z.
Now we can define a member function pointer p for class Y. This is written as:
void (Y::*p)();
(For simplicity, I’ll assume we’re only interested in functions with the signature void f() )
This pointer p can now be used to point to member functions of class Y.
This question (two questions, really) is then:
- Can
pbe used to point to a function in the derived classZ? - Can
pbe used to point to a function in the base classX?
C++03 std, §4.11 2 Pointer to member conversions:
In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn’t ambiguous.
Conversion in the other direction (via
static_cast) is governed by § 5.2.9 9:In short, you can convert from a derived
D::*to a baseB::*if you can convert from aB::*to aD::*, though you can only use theB::*on objects that are of type D or are descended from D.