[try Beta version]
Not logged in

 
Pointers to functions

Jun 16, 2013 at 10:13pm
closed account (NyhkoG1T)
I am working on a class that only has one function that is public and that is the initial call for the end-user. The initial call for the end user would be, for example:
1
2
MyClass myclass;
myclass.initfunction(AfterOutput);


where initfunction prototype would be

 
void MyClass::initfunction(void (*func)());


and AfterOutput parameter would be a function.

I have a private prototype as follows:
 
void (*pFunc)();


My issue is, for the life of me, inside initfunction I cannot seem to properly do
 
pFunc = func;


which would allow the private internals of MyClass to run the AfterOutput function. How would I go about doing this? I hope I have worded this question effectively and properly. If you need me to, I can post the entirety of the code.

This wouldn't be an issue if the class was defined inside the same source file, however, the class is prototyped and defined separately inside a header file.

EDIT: Sorry for the post. I was assigning func to pFunc to far down in the code and it wasn't being assigned before a loop hit. Had to walk away for a minute to see that.
Last edited on Jun 16, 2013 at 10:44pm
Jun 16, 2013 at 10:20pm
Instead of this bla..bla..bla.. please show a sample code that demonstrates the problem.
Jun 17, 2013 at 2:08am
If you're using C++11, it's a lot easier to use function objects:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <functional>

class MyClass
{
public:
    typedef std::function<void()>  callback;

    void initfunction( callback func )
    {
        pFunc = func;
    }

private:
    callback pFunc;
};

//...
//  when you want to call pFunc
//

void MyClass::someFunctionThatCallspFunc()
{
    pFunc();  // <- it's that easy
}
Topic archived. No new replies allowed.