1

i have made a sample example, in this i'm trying to pass a function as argument i am getting error, could you please help me

typedef void (*callbackptr)(int,int);

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

    void add(int i,callbackptr ptr)
    {
        ptr(i,3);
    }

};

class Mysec
{
public:
    Myfirst first_ptr;
    Mysec();
    ~Mysec();

    void TestCallback()
    {

        callbackptr pass_ptr = NULL;
        pass_ptr = &Mysec::Testing;
        first_ptr.add(2,&Mysec::Testing);
    }

    void Testing(int a,int b)
    {
      int c = a+b;
    }

};

3 Answers 3

4

The type of the callback function you're passing as parameter is not defined as part of a class. You probably should define Testing as static.

Sign up to request clarification or add additional context in comments.

2 Comments

could you please update in my code and repost.. as this is very important now for me please...
static void Testing(int a,int b); void MySec::Testing(int a,int b) // declare following your class { int c = a+b; }
3

You are geting an error because you are pointing to a member function. Pointers to member functions are different. See here: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1

A member function needs to know what instance it is working with (the this pointer) so it can't be called like any other function. If you moved the callback function out of the class (or made it static, which is similar to moving it out of the class) you could call it like any other function.

A more modern way of doing this is to use functors, e.g. boost::function and something like boost::bind :

C++ Functors - and their uses

how boost::function and boost::bind work

Those can hide the difference between member and global functions.

Comments

0

You are trying to access a member function pointer here, using a simple function pointer typedef, which will not work. Let me explain.

When you write a normal, non-member function (similar to C), the function's code actually exists in a location indicated by the name of the function - which you would pass to a function pointer parameter.

However, in the case of a member function, all you have is the class definition; you don't have the actual instance of the class allocated in memory yet. In such a function, since the

this
pointer is not yet defined, any reference to member variables wouldn't make sense, since the compiler doesn't have enough information to resolve their memory locations. In fact, member function pointers are not exact addresses; they encode more information than that (which may not be visible to you). For more, read Pointers to Member Functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.