Christian
Christian

Reputation: 1552

Passing Void into a class as a pointer then executing its contents

How can I pass a function as an argument and then execute it. I'm trying to do something like this:

class Foo{
private:
    void (*external);
public:
    Foo(void (*function)()){ *external = *function; }
    ~Foo(){ }
    bool Execute(){ 
        *external(); // Somehow execute 'external' which does the same thing with 'function' 
        return true
    }
};

void pFnc(){
printf("test");
}


int main(){
 Foo foo = Foo(&pFnc);
 foo.Execute();
 return 0;
}

This is not working of course.

Upvotes: 1

Views: 186

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308520

Try:

    void (*external)();

Your original declaration is a pointer to void, not a pointer to a function returning void.

Upvotes: 2

jpalecek
jpalecek

Reputation: 47770

Set it with

external = function;

and execute with

external();

Also, external has to be declared as a function pointer void (*external)(). Otherwise, you have to cast between function- and void-pointer.

Upvotes: 1

John Dibling
John Dibling

Reputation: 101494

You were close.

class Foo
{
public:
    typedef void(*FN)(void);
    Foo(FN fn) : fn_(fn) {};
    bool Execute()
    {
        fn_();
        return true;
    }
    FN fn_;
};

void pFunc(){
    printf("test");
}

int main()
{
    Foo foo(&pFunc);
    foo.Execute();
}

Upvotes: 2

Related Questions