A function pointer to a member function that is a member of a class

Hello,

How can I create a function pointer that is in a class that points to another member of that same class (so I can switch out "strategies" without checking some boolean)?

When I have this declaration in the class header:

void (Scene::*m_pRenderFunc)();

I can initialize it but I cannot call it (it doesn't compile).

This

(*m_pRenderFunc)();

Does not work.

Thank you for any help you can offer.
It's a member function, so you need to give it a this pointer:

1
2
Scene someScene;
someScene.(*m_pRenderFunc)();
Well, I want to call it from another member function of that same class.
using the "this" keyword to replicate what you showed in the class didn't work.
(this->*m_pRenderFunc)();
You need the -> operator for the "this" keyword.
this->(*m_pRenderFunc)();
Look up operator ->. and operator *.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
struct Scene
{
    void (Scene::*m_pRenderFunc)();
    Scene() : m_pRenderFunc(&Scene::fn1) {}
    void fn1() {
        std::cout << "fn1 is called\n";
    }
    void fn2() {
        (this->*m_pRenderFunc)();
    }
};
int main()
{
    Scene sc;
    sc.fn2();
}

demo: http://ideone.com/ax4fs
That worked! I misplaced my parenthesis.
Thanks for the help!
Topic archived. No new replies allowed.