Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to pass a pointer to a function between classes

Tags:

c++

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?

like image 716
Chris Avatar asked Jan 27 '09 19:01

Chris


1 Answers

your syntax is correct for a C style function pointer. Change it to this:

Derived(string (MainClass::*funPtr)(int)) : strFunction(funPtr) {}

and

string (MainClass::*strFunction)(int value);

remember to call strFunction, you will need an instance of a MainClass object. Often I find it useful to use typedefs.

typedef string (MainClass::*func_t)(int);
func_t strFunction;

and

Derived(func_t funPtr) : strFunction(funPtr) {}
like image 117
Evan Teran Avatar answered Oct 01 '22 16:10

Evan Teran