title: How do I implement a callback in C++?
body: <p>I want to implement a class in c++ that has a callback. </p>
  
  <p>So I think I need a method that has 2 arguments:</p>
  
  <ul>
  <li>the target object. (let's say
  *myObj)</li>
  <li>the pointer to a member function of
  the target object. (so i can do
  *myObj->memberFunc(); )</li>
  </ul>
  
  <p>The conditions are:</p>
  
  <ul>
  <li><p>myObj can be from any class.</p></li>
  <li><p>the member function that is gonna be the callback function is non-static. </p></li>
  </ul>
  
  <p>I've been reading about this but it seems like I need to know the class of myObj before hand. But I am not sure how to do it. How can I handle this? Is this possible in C++?</p>
  
  <p>This is something I have in mind but is surely incorrect.</p>
  
  <pre><code>class MyClassWithCallback{
  public
      void *targetObj;
      void (*callback)(int number);
      void setCallback(void *myObj, void(*callbackPtr)(int number)){
          targetObj = myObj;
          callback = callbackPtr;
      };
      void callCallback(int a){
          (myObj)-&gt;ptr(a);
      };
  };
  class Target{
  public
      int res;
      void doSomething(int a){//so something here. This is gonna be the callback function};        
  };
  
  int main(){
      Target myTarget;
      MyClassWithCallback myCaller;
      myCaller.setCallback((void *)&amp;myTarget, &amp;doSomething);
  </code></pre>
  
  <p>}</p>
  
  <p>I appreciate any help. </p>
  
  <p>Thank you.</p>
  
  <p>UPDATE
  Most of you said Observing and Delegation, well that's i exactly what i am looking for, I am kind of a Objective-C/Cocoa minded guy.
  My current implementation is using interfaces with virtual functions. Is just I thought it would be "smarter" to just pass the object and a member function pointer (like boost!) instead of defining an Interface. But It seems that everybody agrees that Interfaces are the easiest way right? Boost seems to be a good idea, (assuming is installed)</p>