Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a function in a member of class? (Using function as callback)

I want to store a function as a class member and call it inside the class? Pretty much like a callback function. My class draw a document but every document must drawn differently. So I want to assign a function (written outside of the class) into one of the members of the class and then call it when I want to draw the document.

This function mostly is responsible for transforming objects according to each specific document.

Here is my class:

class CDocument
{
public:
    CDocument();
    ~CDocument();

    void *TransFunc();
}

void Transform()
{

}

int main()
    CDocument* Doc = new CDocument();
    Doc->TransFunc = Transform();
}

I know that this is probably simple question, but I couldn't find the answer by googling or searching SO.

like image 492
bman Avatar asked Dec 05 '25 13:12

bman


1 Answers

I think, this is what you might want. Please get back to me if you have questions.

class CDocument
{
public:
    CDocument():myTransFunc(NULL){}
    ~CDocument();

    typedef void (*TransFunc)();  // Defines a function pointer type pointing to a void function which doesn't take any parameter.

    TransFunc myTransFunc;  //  Actually defines a member variable of this type.

    void drawSomething()
    {
         if(myTransFunc)
            (*myTransFunc)();   // Uses the member variable to call a supplied function.
    }
};

void Transform()
{

}

int main()
{
    CDocument* Doc = new CDocument();
    Doc->myTransFunc = Transform;  // Assigns the member function pointer to an actual function.
}
like image 171
PermanentGuest Avatar answered Dec 08 '25 04:12

PermanentGuest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!