1

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.

Community
  • 1
  • 1
PHcoDer
  • 1,166
  • 10
  • 23
  • You should better use the _Template Function Pattern_ than a function pointer for such cases. – πάντα ῥεῖ Nov 23 '16 at 17:28
  • Are you suggesting there is not solution for this. Apart from using Template Function Pattern? – PHcoDer Nov 23 '16 at 17:29
  • I suggest that would be the better and more straightforward solution (and probably less error prone). – πάντα ῥεῖ Nov 23 '16 at 17:32
  • Okay Thanks. However, proceeding with that now will make me do a lot of change in the code base. Do you have any idea about solution for the above situation? – PHcoDer Nov 23 '16 at 17:34
  • You'll need a pointer to the derived class object to call that function pointer correctly, so effectively you'll need to know the derived class type, that you can cast `this` to it. May be a template function (not to confuse with the mentioned _Template Function Pattern_) could be a viable solution. – πάντα ῥεῖ Nov 23 '16 at 17:41
  • 1
    Show some actual code and say _what_ didn't work, if you want help. Currently it's not at all clear what problem you're having. – Useless Nov 23 '16 at 18:21

3 Answers3

3

Simply use:

(this->*fncPtr)();

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

Chor Sipahi
  • 546
  • 3
  • 10
1

Given a pointer to member function of Derived:

void (Derived::*derivedFncPtr)() = &Derived::someMemberFunction;

First, cast it to a pointer to member function of Base:

void (Base::*baseFncPtr)() = static_cast<void (Base::*)()>(derivedFncPtr);

Then, call it: (assuming *this is a Base with dynamic type Derived)

(this->*baseFncPtr)();

Live example

Oktalist
  • 14,336
  • 3
  • 43
  • 63
1

If you have a pointer to member function of base void (Base::*fncPtr)(), you can call it with a pointer to derived object this in exactly the same way as you would call a pointer to member function of that same derived class.

(this->*fncPtr)();

Demo here


(((Base)this)->*fncPtr)();

You can explicitly cast this to a pointer of Base if you really want to (it's not required), but this is not how it is done since Base is not a pointer type. This would work:

((Base*)this)->*fncPtr)();

But as I said, the cast is redundant.

eerorika
  • 232,697
  • 12
  • 197
  • 326