fork(1) download
  1. class Consumer {
  2. public:
  3. virtual void consume(int data) = 0;
  4. };
  5.  
  6. class A {
  7. public:
  8. A() {}
  9. void attachConsumer(Consumer* consumer) { consumer_ = consumer; }
  10. void process(int data) {
  11. // must always check consumer_ here!
  12. consumer_->consume(data); }
  13. private:
  14. Consumer* consumer_;
  15. };
  16.  
  17. class B : public Consumer {
  18. public:
  19. B() {}
  20. void consume(int data) { /* consume data */ }
  21. };
  22.  
  23. int main() {
  24. A a_ = A();
  25. // ... for reasons I won't tell you, B must be created later than A ...
  26. B* b_ = new B();
  27. a_.attachConsumer(b_);
  28. a_.process(5);
  29. return 0;
  30. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty