fork(3) download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. class myClass
  6. {
  7. public:
  8. myClass(int value);
  9.  
  10. void methodA(const string &msg) { cout << msg << " from methodA" << endl; }
  11. void methodB(const string &msg) { cout << msg << " from methodB" << endl; }
  12. void method(const string &msg) { (this->*send_msg)(msg); }
  13.  
  14. //private:
  15. void (myClass::*send_msg)(const string &msg);
  16. };
  17.  
  18. myClass::myClass(int value) : send_msg(value > 0 ? &myClass::methodA : &myClass::methodB)
  19. {
  20.  
  21. }
  22.  
  23. int main()
  24. {
  25. myClass a(1);
  26. a.method("Hi");
  27.  
  28. myClass b(0);
  29. b.method("Hi");
  30.  
  31. //or
  32.  
  33. myClass c(1);
  34. (c.*c.send_msg)("Hi");
  35.  
  36. myClass * p = new myClass(0);
  37. (p->*p->send_msg)("Hi");
  38. delete p;
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Hi from methodA
Hi from methodB
Hi from methodA
Hi from methodB