fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class Base
  5. {
  6. public:
  7. virtual ~Base() { }
  8.  
  9. virtual void Print() const { std::cout << "Base\n"; }
  10. virtual Base* Clone() const = 0;
  11. };
  12.  
  13. class Derived : public Base
  14. {
  15. public:
  16.  
  17. void Print() const { std::cout << "Derived\n"; }
  18. Derived* Clone() const { return new Derived(*this); }
  19. };
  20.  
  21. class Container
  22. {
  23. private:
  24. std::vector<Base*> m_collection;
  25. public:
  26. void Add(const Base& objectToAdd)
  27. {
  28. Base* copyOfBase = objectToAdd.Clone();
  29. m_collection.push_back(copyOfBase);
  30. }
  31.  
  32. Base* GetObjectAtIndex(int index) const
  33. {
  34. return index < m_collection.size() ? m_collection.at(index) : NULL;
  35. }
  36.  
  37. ~Container()
  38. {
  39. for (auto &obj : m_collection)
  40. {
  41. delete obj;
  42. }
  43.  
  44. m_collection.clear();
  45. }
  46. };
  47.  
  48. int main(int argc, const char* argv[])
  49. {
  50. Container myContainer;
  51.  
  52. Derived derivedObject;
  53.  
  54. myContainer.Add(derivedObject);
  55.  
  56. Base* retrievedObject = myContainer.GetObjectAtIndex(0);
  57.  
  58. if (retrievedObject)
  59. {
  60. retrievedObject->Print();
  61. }
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Derived