0

i want to have a class member which is a pointer to undefined typical function .
the function must be performed by user. the user must pass the function as a parameter to class constructor. the function is called in the scope of class methodes. can i do these tasks like this ?

class MyClss
{
    private:    
    bool (*f)();

    public:
    MyClss(bool (*fp)());
    void MyMethod();
}

MyClss::MyClss(bool (*fp)())
{
    f = fp;
}

void MyClss::MyMethod()
{
    // do tasks
    if(f())
    {
        // do tasks
    }
}
MAB
  • 19
  • 4

1 Answers1

0

The code you have given will works fine. See the code below it is the same but using std::function from <functional> header file.

#include <functional>

// The function prototype.
typedef std::function<bool()> MyFunction;

class MyClss
{
    private:    
    MyFunction f;

    public:
    MyClss(MyFunction fp);
    void MyMethod();
};

MyClss::MyClss(MyFunction fp)
{
    f = fp;
}

void MyMethod()
{
    // do tasks
    if(f())
    {
        // do tasks
    }
}
Mohit
  • 1,225
  • 11
  • 28
  • 1
    Please read [using std is bad practive](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Ed Heal Apr 15 '18 at 08:51