Smith Smith - 1 year ago 69
C++ Question

Call base method from inherited function pointer

My base class contains a function pointer to a member function. How can I call this member function from the derived class? I want to call this function by its pointer.
Here is my code so far:

#include <iostream>

class Base
Base() {FuncPtr = &Base::Func1;}
Base(int num) {
FuncPtr = &Base::Func1;
else if(num==2)
FuncPtr = &Base::Func2;
FuncPtr = NULL;
void (Base::*FuncPtr)(float ,float );

void Func1(float x,float y) { std::cout << "Func1 called\n";}
void Func2(float x,float y) { std::cout << "Func2 called\n";}

class Derived : private Base
Derived() {}
Derived(int num) : Base(num) {}

void callBaseFunc1 (float x,float y) { this->Func1 (x,y);} // works
void callBaseFuncViaPtr (float x,float y) { this->(*FuncPtr)(x,y);} // wrong ...

int main()
Derived Test;

Test.callBaseFunc1 (2.72f,3.14f); // works
Test.callBaseFuncViaPtr (2.72f,3.14f); // syntax error in function declaration...

return 0;


Answer Source

You almost had it, just move the parens:

void callBaseFuncViaPtr (float x,float y) { (this->*FuncPtr)(x,y);}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download