0

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

1
  • 2
    If you tried, then you should tell what failed or what worked ;). Commented Mar 3, 2012 at 9:10

3 Answers 3

3

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)();
 }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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); 
  }  
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.