bman
bman

Reputation: 5235

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.

Upvotes: 3

Views: 5835

Answers (3)

Bo Persson
Bo Persson

Reputation: 92261

The C declaration syntax, inherited by C++, is tricky.

Your declaration

void *TransFunc();

is actually the same as

void* TransFunc();

which declares a function returning a pointer, and not a pointer to a function.

To have the * bind to the declared name, and not to the type, you have to use an extra set of parenthesis

void (*TransFunc)();

Upvotes: 0

Alok Save
Alok Save

Reputation: 206528

You need to use a Pointer to member function.

typedef void (CDocument::*TransFuncPtr)();

And then you can use TransFuncPtr as an type.


With your edit It seems like you just need a Pointer to a Free function.
Here is a small working sample.

#include<iostream>
#include<string>

typedef void (*TransFuncPtr)();

class Myclass
{
     public:
     TransFuncPtr m_funcPtr;
};

void doSomething(){std::cout<<"Callback Called";}

int main()
{
    Myclass obj;
    obj.m_funcPtr = &doSomething;
    obj.m_funcPtr();
    return 0;
}

Upvotes: 3

PermanentGuest
PermanentGuest

Reputation: 5331

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.
}

Upvotes: 5

Related Questions