Smith Smith - 3 months ago 7
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
{
public:
Base() {FuncPtr = &Base::Func1;}
Base(int num) {
if(num==1)
FuncPtr = &Base::Func1;
else if(num==2)
FuncPtr = &Base::Func2;
else
FuncPtr = NULL;
}
protected:
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
{
public:
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...

getchar();
return 0;
}


Thanks

Answer

You almost had it, just move the parens:

void callBaseFuncViaPtr (float x,float y) { (this->*FuncPtr)(x,y);}