I’m attempting to pass a pointer to a function that is defined in one class into another class. After much research, I believe my syntax is correct, but I am still getting compiler errors. Here is some code which demonstrates my issue:
class Base { public: BaseClass(); virtual ~BaseClass(); }; class Derived : public Base { public: // assign strFunction to the function pointer passed in Derived(string (*funPtr)(int)) : strFunction(funPtr); ~Derived(); private: // pointer to the function that is passed in string (*strFunction)(int value); }; class MainClass { public: MainClass() { // allocate a new Derived class and pass it a pointer to myFunction Base* myClass = new Derived(&MainClass::myFunction); } string myFunction(int value) { // return a string } };
When I try to compile this code, the error I get is
error: no matching function for call to ‘Derived::Derived(string (MainClass::*)(int))’
followed by
note: candidates are: Derived::Derived(string (*)(int))
Any idea what I might be doing wrong?
your syntax is correct for a C style function pointer. Change it to this:
and
remember to call
strFunction, you will need an instance of a MainClass object. Often I find it useful to use typedefs.and