Pure Virtual Class and Collections (vector?)

社会主义新天地 提交于 2019-12-01 03:48:18

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!