You need to use an array of pointers to Shape
or better yet use an STL container of smart pointers to Shape
. Something like:
#include <vector>
#include <memory>
struct Shape {
virtual ~Shape() = 0;
};
Shape::~Shape(){}
struct Square : public Shape {
};
class List {
std::vector<std::unique_ptr<Shape>> shapes;
public:
int getCount() const {return shapes.size();}
const Shape* getItem(int index) const;
void insert(std::unique_ptr<Shape>, int index);
};
const Shape*
List::getItem(int index) const {
if (index < 0 || (size_t) index >= shapes.size())
return nullptr;
return shapes[index].get();
}
void
List::insert(std::unique_ptr<Shape> sh, int index) {
if (index < 0)
return;
if ((size_t)index >= shapes.size())
index = shapes.size();
shapes.insert(shapes.begin() + index, std::move(sh));
}
int main() {
List list;
list.insert(std::unique_ptr<Shape>(new Square()), 0);
list.insert(std::unique_ptr<Shape>(new Square()), 0);
list.insert(std::unique_ptr<Shape>(new Square()), 2);
const Shape* sh = list.getItem(0);
}
Or better still, if possible, don't write your own List
class just use an STL container of smart pointers directly instead!