Pure Virtual Class and Collections (vector?)

Use covariant return types. See FAQ 20.8 for your clone methods. You can rely on the factory method as well to create the Shape objects.

Also, you cannot have a container of abstract class objects, abstract classes cannot be instantiated. Instead, create a container of pointers/references to derived concrete objects. Note, if you are using pointer, it becomes your responsibility to clear them. The container will not de-allocate the memory properly. You can use smart pointers instead of raw pointers to handle this more efficiently. Look up scoped_ptr and shared_ptr from Boost.


When you need polymorphism, you need to use either pointers or references. Since containers (or arrays) can't store references, you have to use pointers.

Essentially change your picture class's vector to:

std::vector<Shape*>

and appropriately modify the other member functions.

The reason why you can't/shouldn't store them as value types is because vector is a homogenous container i.e. it only stores data of one type (and only one type -- subclasses are not allowed!). The reason for this is because the vector stores its data in an array, which needs to know the size of the objects it's storing. If the sizes of these objects are different (which they might be for different shapes) then it can't store them in an array.

If you store them as pointers then they all have the same size (sizeof(Shape*)) and also have access to the shape's vtable, which is what allows polymorphic behaviour.