#include <iostream>
#include <vector>
class Base
{
public:
virtual ~Base() { }
virtual void Print() const { std::cout << "Base\n"; }
virtual Base* Clone() const = 0;
};
class Derived : public Base
{
public:
void Print() const { std::cout << "Derived\n"; }
Derived* Clone() const { return new Derived(*this); }
};
class Container
{
private:
std::vector<Base*> m_collection;
public:
void Add(const Base& objectToAdd)
{
Base* copyOfBase = objectToAdd.Clone();
m_collection.push_back(copyOfBase);
}
Base* GetObjectAtIndex(int index) const
{
return index < m_collection.size() ? m_collection.at(index) : NULL;
}
~Container()
{
for (auto &obj : m_collection)
{
delete obj;
}
m_collection.clear();
}
};
int main(int argc, const char* argv[])
{
Container myContainer;
Derived derivedObject;
myContainer.Add(derivedObject);
Base* retrievedObject = myContainer.GetObjectAtIndex(0);
if (retrievedObject)
{
retrievedObject->Print();
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgoKY2xhc3MgQmFzZQp7CnB1YmxpYzoKICAgIHZpcnR1YWwgfkJhc2UoKSB7IH0KCiAgICB2aXJ0dWFsIHZvaWQgUHJpbnQoKSBjb25zdCB7IHN0ZDo6Y291dCA8PCAiQmFzZVxuIjsgfQogICAgdmlydHVhbCBCYXNlKiBDbG9uZSgpIGNvbnN0ID0gMDsKfTsKCmNsYXNzIERlcml2ZWQgOiBwdWJsaWMgQmFzZQp7CnB1YmxpYzoKCiAgICB2b2lkIFByaW50KCkgY29uc3QgeyBzdGQ6OmNvdXQgPDwgIkRlcml2ZWRcbiI7IH0KICAgIERlcml2ZWQqIENsb25lKCkgY29uc3QgeyByZXR1cm4gbmV3IERlcml2ZWQoKnRoaXMpOyB9Cn07CgpjbGFzcyBDb250YWluZXIKewpwcml2YXRlOgogICAgc3RkOjp2ZWN0b3I8QmFzZSo+IG1fY29sbGVjdGlvbjsKcHVibGljOgogICAgdm9pZCBBZGQoY29uc3QgQmFzZSYgb2JqZWN0VG9BZGQpCiAgICB7CiAgICAgICAgQmFzZSogY29weU9mQmFzZSA9IG9iamVjdFRvQWRkLkNsb25lKCk7CiAgICAgICAgbV9jb2xsZWN0aW9uLnB1c2hfYmFjayhjb3B5T2ZCYXNlKTsKICAgIH0KCiAgICBCYXNlKiBHZXRPYmplY3RBdEluZGV4KGludCBpbmRleCkgY29uc3QKICAgIHsKICAgICAgICByZXR1cm4gaW5kZXggPCBtX2NvbGxlY3Rpb24uc2l6ZSgpID8gbV9jb2xsZWN0aW9uLmF0KGluZGV4KSA6IE5VTEw7CiAgICB9CgogICAgfkNvbnRhaW5lcigpCiAgICB7CiAgICAgICAgZm9yIChhdXRvICZvYmogOiBtX2NvbGxlY3Rpb24pCiAgICAgICAgewogICAgICAgICAgICBkZWxldGUgb2JqOwogICAgICAgIH0KCiAgICAgICAgbV9jb2xsZWN0aW9uLmNsZWFyKCk7CiAgICB9Cn07CgppbnQgbWFpbihpbnQgYXJnYywgY29uc3QgY2hhciogYXJndltdKQp7CiAgICBDb250YWluZXIgbXlDb250YWluZXI7CgogICAgRGVyaXZlZCBkZXJpdmVkT2JqZWN0OwoKICAgIG15Q29udGFpbmVyLkFkZChkZXJpdmVkT2JqZWN0KTsKICAgIAogICAgQmFzZSogcmV0cmlldmVkT2JqZWN0ID0gbXlDb250YWluZXIuR2V0T2JqZWN0QXRJbmRleCgwKTsKCiAgICBpZiAocmV0cmlldmVkT2JqZWN0KQogICAgewogICAgICAgIHJldHJpZXZlZE9iamVjdC0+UHJpbnQoKTsKICAgIH0KCiAgICByZXR1cm4gMDsKfQ==