Home > Software engineering >  Function pointer inside class point to that class's member function
Function pointer inside class point to that class's member function

Time:07-26

I am familiar with the function pointer to class member issue, which requires the signature to be ClassName::*FuncPtr, but I have this nuanced problem where I need the function pointer to be to a containing class member:

class F
{
public:
    class Container;
    typedef void (Container::*FuncPtr)();
    
    F(FuncPtr fp) : m_fp(fp) {}
    void Execute() { (*this.*m_fp)(); }
private:
    FuncPtr m_fp;
};

class Container
{
public:
    Container() : fps(&Container::Func) { }
    void Func() { }
private:
    F fps;
};

So, basically I want to create an object Container, which will send in its constructor a pointer to one of its member functions to the F object it contains, which should store that function pointer.

CodePudding user response:

You need to move the forward declaration class Container; outside of F. Inside of F, it is declaring F::Container, which is a different type than Container.

Also, (*this.*m_fp)() (alternatively (this->*m_fp)()) won't work at all, as m_fp is expecting a Container object on the left side of .* (or ->*), but this is pointing at an F object instead. So Container will have to pass its this pointer to F's constructor to be stored along with m_fp.

Try this:

#include <iostream>
using namespace std;

class Container;

class F
{
public:
    typedef void (Container::*FuncPtr)();
    
    F(Container &c, FuncPtr fp) : m_c(c), m_fp(fp) {}
    void Execute() { (m_c.*m_fp)(); }
private:
    Container& m_c;
    FuncPtr m_fp;
};

class Container
{
public:
    Container() : fps(*this, &Container::Func) { }
    void Func() { ... }
private:
    F fps;
};

Online Demo

  •  Tags:  
  • c
  • Related