fork(1) download
  1. #include <iostream>
  2.  
  3. class Bar;
  4. class Foo {
  5. public:
  6. Foo() : a_(0) {};
  7. Foo(int a) : a_(a) {};
  8. Foo(const Bar& bar_);
  9.  
  10. inline int getA() { return a_; };
  11. virtual void print();
  12. private:
  13. int a_;
  14. Foo* foo;
  15. };
  16.  
  17. class Bar : public Foo {
  18. public:
  19. Bar() : Foo(), b_(0) {};
  20. Bar(int a, int b) : Foo(a), b_(b) {};
  21. inline int getB() { return b_; };
  22. virtual void print() override { std::cout << "{a: " << getA() << ", b: " << getB() << "}\n"; };
  23. private:
  24. int b_;
  25. };
  26.  
  27. Foo::Foo(const Bar& bar_) {
  28. foo = new Bar(bar_);
  29. }
  30.  
  31. void Foo::print() {
  32. if (foo == 0)
  33. std::cout << "{a: " << getA() << "}\n";
  34. else
  35. foo->print();
  36. };
  37.  
  38. int main() {
  39. Foo t1 = Bar(10,10);
  40. Bar t2 = Bar(20,20);
  41. Foo *t3 = new Bar(30,30);
  42. t1.print();
  43. t2.print();
  44. t3->print();
  45. delete t3;
  46. return 0;
  47. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
{a: 10, b: 10}
{a: 20, b: 20}
{a: 30, b: 30}