Function pointers, function pointers, and pointer Functions
(1/2) Type
A normal function pointer cannot be assigned the address of a member function.
Int (* pFunc )();
PFunc is a function pointer, while int (*) () is a type.
The member function address must be assigned to the member function pointer.
class Base{public: int func() { return 1; }};int main(){ int (*pFunc)(); pFunc = &Base::func; //error: cannot convert 'int (Base::*)()' to 'int (*)()' in assignment return 0;}
class Base{public: int func() { return 1; }};int main(){ int (Base::*pFunc)(); // OK pFunc = &Base::func; return 0;}
Again:
class Base{public: int func() { return 1; }};class Derived : public Base{public: int foo() { return 1; }};int main(){ typedef int (Base::*FuncPtr)(); FuncPtr fPtr = &Derived::foo; // error return 0;}
Mandatory type conversion required
......
FuncPtr fPtr = (FuncPtr)&Derived::foo; // OK
In turn, the base class member function address can be assigned a pointer to the member function of the derived class.
class Base{public: int func() { return 1; }};class Derived : public Base{public: int foo() { return 1; }};int main(){ typedef int (Derived::*FuncPtr)(); FuncPtr fPtr = &Base::func; // OK return 0;}(2/2) Call
class Base{public: virtual void func(int i) { cout << "Base: " << i << endl; }};class Derived : public Base{public: virtual void func(int i) { cout << "Derived: " << i << endl; }};int main(){ typedef void (Base::*FuncPtr)(int); FuncPtr fPtr = &Base::func; Base b; (b.*fPtr)(2); Derived* dPtr = new Derived(); (dPtr->*fPtr)(2); Base* bPtr = new Derived(); (bPtr->*fPtr)(2); return 0;}
Output:
Base: 2
Derived: 2
Derived: 2