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

};
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
Naruto
  • 9,476
  • 37
  • 118
  • 201

3 Answers3

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.

littleadv
  • 20,100
  • 2
  • 36
  • 50
  • could you please update in my code and repost.. as this is very important now for me please... – Naruto Mar 22 '11 at 06:16
  • static void Testing(int a,int b); void MySec::Testing(int a,int b) // declare following your class { int c = a+b; } – Guy Sirton Mar 22 '11 at 06:35
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.

Community
  • 1
  • 1
Guy Sirton
  • 8,331
  • 2
  • 26
  • 36
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.
brado86
  • 184
  • 3