Riskhan
Riskhan

Reputation: 4470

Passing function name as parameter of Another function in C++ class

I have two classes A and B. I want to pass a function name in class A as parameter of function in Class B. I tried with below sample, Is it correct way.

class A
{
  public:
  B m_b;

  void MyFun()
  {
      // do something
  }

  void Test()
  {
  m_b.Process( MyFun );
  } 
}


class B
{
 public:
 void Process( void (*f)() )
 {
   (*f)();
 }
}

thanks in advance

Upvotes: 0

Views: 2005

Answers (3)

Sami
Sami

Reputation: 570

Follow the advice here: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.4, you'll end up with this:

class A;
typedef void (A::*MemFun)();

class B 
{ 
 public: 
 void Process(A& a, MemFun mf) 
 { 
   (a.*mf)(); 
 } 
}; 

class A 
{ 
  public: 
  B m_b; 

  void MyFun() 
  { 
    // do something 
  } 

  void Test() 
  { 
    MemFun p = &A::MyFun;
    A a;
    m_b.Process(a, p); 
  }  
};

Upvotes: 1

casablanca
casablanca

Reputation: 70701

Since MyFun is a member function of class A, you need a pointer-to-member instead of a regular function pointer, and you also need an instance of class A to invoke the function on:

class B
{
 public:
 void Process(A *obj, void (A::*f)() )
 {
   (obj->*f)();
 }
}

Upvotes: 3

Benoit
Benoit

Reputation: 79175

Actually, if MyFun is not a static member of your class, it has a hidden argument that is of type A*, so this is implemented like: m_a.MyFun(...) =~ MyFunImpl(&m_a, ...).

So, What you want is probably have a static function MyFun (you can't use this inside it), and inside B::Process call f().

If you need to pass this, refer to casablanca's answer (pointers to member functions).

Otherwise, if you want to pass an argument, you can lookup std::bind or lambda functions (C++0x), or boost::bind prior to that.

Upvotes: 1

Related Questions