C++ Call Pointer To Member Function

user1670407 picture user1670407 · Feb 11, 2013 · Viewed 35.1k times · Source

I have a list of pointers to member functions but I am having a difficult time trying to call those functions... whats the proper syntax?

typedef void (Box::*HitTest) (int x, int y, int w, int h);

for (std::list<HitTest>::const_iterator i = hitTestList.begin(); i != hitTestList.end(); ++i)
{
    HitTest h = *i;
    (*h)(xPos, yPos, width, height);
}

Also im trying to add member functions to it here

std::list<HitTest> list;

for (std::list<Box*>::const_iterator i = boxList.begin(); i != boxList.end(); ++i)
{
    Box * box = *i;
    list.push_back(&box->HitTest);
}

Answer

Drew Dormann picture Drew Dormann · Feb 11, 2013

Pointers to non-static members are a unique beast with unique syntax.

Those functions need to be supplied a this pointer, so you must have the Box pointer handy that will be used as this.

(box->*h)(xPos, yPos, width, height);