Question

Ok here is pseudo-code showing the problem. I want to pass on the Man's sayAh() method to the Dog instance.

class Man
{
public:
    void haveDogBiteYou(){
        Dog *mydog = new Dog();
        myDog->setCallback(&this->sayAh); // How???
        myDog->bite();
    }

    void sayAh(){
        cout << "AHHHHHH!";
    }
}



class Dog{
public:

    void (*callbackFunc)(void);

    void setCallback(void (*callbackFunc)(void)){
        this->callbackFunc=callbackFunc;
    }

    void bite(){
        callbackFunc();
    }

}

I'd like to have the code setup in a way that if I have another class like Kid (i.e., Man's subclass), I can pass on the callback to a method member of that function as well. So probably changing

void (*callbackFunc)(void);

to

void (Man::*callbackFunc)(void);

will not be an answer to this problem... By the way, I am open to other solutions... Something like Java's interface works great.

Was it helpful?

Solution

Check http://ideone.com/wjRwi4 (and copied below)

But you might need to review how you're doing things:

  • Decide whether to use function pointers (or static member pointers) or method pointers (then you need an object to run the method on).
  • You probably need to think about how you want to apply this to a hierarchy.
  • Alternatively you can try function objects (i.e. a class/struct with an operator() defined).
  • Remember that is always easier if you create a typedef for the function/method pointer.
  • Check http://www.parashift.com/c++-faq/pointers-to-members.html

The code:

#include <iostream>
using namespace std;

class Man;

class Dog{
public:

    Man *man;
    void (Man::*callbackFunc)(void);

    void setCallback(Man *_man,void (Man::*_callbackFunc)(void)){
        callbackFunc=_callbackFunc;
        man=_man;
    }

    void bite();

};

class Man
{
public:
    void haveDogBiteYou(){
        Dog *myDog = new Dog();
        myDog->setCallback(this,&Man::sayAh); // How???
        myDog->bite();
    }

    void sayAh(){
        cout << "AHHHHHH!";
    }
};


void Dog::bite(){
    (man->*callbackFunc)();
}



int main() {
    Man m;
    m.haveDogBiteYou();
    return 0;
}

OTHER TIPS

You can change:

void sayAh(){
    cout << "AHHHHHH!";
}

to a static member function for your needs.

static void sayAh(){
    cout << "AHHHHHH!";
}

If you do that, you can simplify

    myDog->setCallback(this->sayAh);

to

    myDog->setCallback(sayAh);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top