1

My problem is about passing a member function from a Class A, to a member function of a Class B:

I tried something like this :

typedef void (moteurGraphique::* f)(Sprite);
f draw =&moteurGraphique::drawSprite;
defaultScene.boucle(draw);

moteurGraphique is A class, moteurGraphique::drawSprite is A member function,

defaultScene is an instance of B class, and boucle is B member function.

All that is called in a member function of A:

void moteurGraphique::drawMyThings()

I tried different ways to do it, that one seems the more logical to me, but it won't work! I got:

Run-Time Check Failure #3 - The variable 'f' is being used without being initialized.

I think I am doing something wrong, can someone explain my mistake ?

Liam Marshall
  • 1,353
  • 1
  • 12
  • 21

3 Answers3

3

C++11 way:

using Function = std::function<void (Sprite)>;

void B::boucle(Function func);
...

A a;
B b;

b.boucle(std::bind(&A::drawSprite, &a, std::placeholders::_1));
Ivan
  • 2,007
  • 11
  • 15
2

Member functions need to be called on objects, so passing the function pointer alone is not enough, you also need the object to call that pointer on. You can either store that object in the class that is going to call the function, create it right before calling the function, or pass it along with the function pointer.

class Foo
{
public:
    void foo()
    {
        std::cout << "foo" << std::endl;
    } 
};

class Bar
{
public:
    void bar(Foo * obj, void(Foo::*func)(void))
    {
        (obj->*func)();
    }
};

int main()
{
    Foo f;
    Bar b;
    b.bar(&f, &Foo::foo);//output: foo
}
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • I think i would do like that, because i am affraid, other ways wont works. I knew that member functions are attached to executed object,but i wanted a way to dynamicly bind that, Thank you ! – Fabrice Palermo Oct 13 '15 at 09:14
1

Can't you make drawMyThing a static function if you don't need to instantiate A, and then do something like :

defaultScene.boucle(A.drawMyThing(mySpriteThing));

?

Magnas
  • 869
  • 1
  • 5
  • 18