fork(1) download
  1. #include <iostream>
  2. #include <list>
  3. #include <memory>
  4. #include <typeinfo>
  5. using namespace std;
  6.  
  7.  
  8. class Abstract
  9. {
  10. public:
  11. virtual string toString() const = 0;
  12. virtual shared_ptr<Abstract> clone() const= 0;
  13. };
  14.  
  15. class A : public Abstract
  16. {
  17. public:
  18. A(int a, int b) : a(a), b(b)
  19. {}
  20. string toString() const override { return "A"; }
  21. shared_ptr<Abstract> clone() const override { return make_shared<A>(*this); }
  22.  
  23. private:
  24. int a;
  25. int b;
  26. };
  27. class B : public Abstract
  28. {
  29. public:
  30. B(int b) : b(b)
  31. {}
  32. string toString() const { return "B"; }
  33. shared_ptr<Abstract> clone() const override { return make_shared<B>(*this); }
  34. private:
  35. int b;
  36. };
  37.  
  38. class Data
  39. {
  40. public:
  41. Data(const string & name) : name (name)
  42. {}
  43. Data& AddData ( const Abstract & a )
  44. {
  45. //Need to fix next line
  46. l1.push_back(a.clone());
  47. return (*this);
  48. }
  49. void show() const {
  50. for (auto& x: l1)
  51. cout << x->toString()<<"("<< typeid(*x).name()<<") ";
  52. cout <<endl;
  53. }
  54. private:
  55. list<shared_ptr<Abstract>> l1;
  56. string name;
  57. };
  58.  
  59. int main() {
  60. Data test("Random Name");
  61.  
  62. test.AddData(A(1,2))
  63. .AddData(B(3))
  64. .AddData(B(4));
  65. test.show();
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
A(1A) B(1B) B(1B)