Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

easy function pointer question

Hi,

I have two classes, I want to know how one class can set a pointer to a function to another like:

class A {
    void DoSomething();
    void SetFunctionPointer(?); { m_pFunctionPointer = ?; }
    void* m_pFunctionPointer;
};

class B {
     A* m_p;
     void SayHello() { cout << "Hello" << endl; }
};

void A::DoSomething()
{
    m_pFunctionPointer();
}

B::B()
{
    m_p->SetFunctionPointer(&SayHello());
}

Thanks
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
BTW, see also http://www.newty.de/fpt/index.html ("The Function Pointer Tutorials") for more info.
The problem with member function pointers is that you need both the function pointer and an instance of the class the function is a member from. Because of that there are only a few known senseful samples where any one has used member function pointers, You see it in jkr's sample above. He creates a B object before calling the function pointer but the B is any B and has only default initialization. So that B object cannot do any specific things but only that which are valid for all instances of class B. for that purpose you can use static member functions which can be called without needing an instance of B but only with the class prefix:

class B {
public:
     B();
     static  void SayHello() { cout << "In B: Hello" << endl; }
};

You can call it everywhere by simply

         B::SayHello();

And function pointers to static member functions can be treated like function pointers to global functions:

// a typedef makes it simpler to define the type
typedef void (*SayFunc)();

class A
{
      SayFunc  funcPtr;   // we use our typedef here
public:
      A(SayFunc sf) :  funcPtr(sf) { }   // pass it to the constructor        
      void say() {  funcPtr(); }
};

That's all.

Regards, Alex
Try this :

#include <iostream>

using namespace std;

class A;

class B {
  public:
    A* m_p;
    B();
    void SayHello() { cout << "Hello" << endl; }
    ~B();
};

class A {
  private:
    void (B::*m_pFunctionPointer)();
  public:
    void DoSomething();
    void SetFunctionPointer(void (B::*fun_ptr)()) { m_pFunctionPointer = fun_ptr; }
};

void A::DoSomething() {
  B b;
  (b.*m_pFunctionPointer)();
}

B::B() {
  m_p = new A();
  m_p->SetFunctionPointer(&B::SayHello);
}

B::~B() {
  delete m_p;
}

int main(void) {
  B b;
  b.m_p->DoSomething();
  return 0;
}
Oops, should have checked before posting ... that's the trouble when you start writing a reply, and get distracted half way through :)
Hey DJ,

Try this one: its tidy!
http://www.codeproject.com/cpp/Functor.asp


Best Regards,
DeepuAbrahamK