PHcoDer PHcoDer - 15 days ago 9
C++ Question

C++: Calling a function from derived by a function pointer defined in base class

If a function pointer is defined and assigned values in base class. And it has to be used to call a function from a class derived from it. How can we do that?

This shows an example to call functions by pointers. But this works only in case when pointer is defined in same class from where it is being used.

This shows example to call parent class function. I tried some this similar but it didn't work.

From derived
(((Base)this)->*fncPtr)();
(((Base)this)->*(Base::fncPtr))();


Both of the above doesn't work. Please help me out.

Answer

Simply use:

(this->*fncPtr)();

Nothing else is required. Cast to base type is implicit. So you do not need to cast it explicitly.