fork download
  1. #include <iostream>
  2.  
  3. class MyClass
  4. {
  5. public:
  6.  
  7. MyClass (const bool select)
  8. {
  9. if (select)
  10. {
  11. speaker = &MyClass::foo;
  12. }
  13. else
  14. {
  15. speaker = &MyClass::bar;
  16. }
  17. }
  18.  
  19. void speak() const
  20. {
  21. (this->*speaker)();
  22. }
  23.  
  24. void (MyClass::*speaker)() const;
  25.  
  26. private:
  27. void foo() const { std::cout << "Foo\n"; }
  28. void bar() const { std::cout << "Bar\n"; }
  29. };
  30.  
  31. int main()
  32. {
  33. MyClass m1(true);
  34. MyClass m2(false);
  35.  
  36. m1.speak();
  37. m2.speak();
  38. }
  39.  
  40.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Foo
Bar