Some times we have to put different objects in the same hierarchy in one container. I read some article saying there are some tricks and traps. However, I have no big picture about this question. Actually, this happens a lot in the real word.
For example, a parking lot has to contain different types of cars; a zoo has to contain different types of animals; a book store has to contain different types of books.
I remember that one article saying neither of the following is a good design, but I forgot where it is.
vector<vehicle> parking_lot;
vector<*vehicle> parking_lot;
Can anybody offer some basic rules for this kind of question?
The problem with
vector<vehicle>is that the object only holds vehicles. The problem withvector<vehicle*>is that you need to allocate and, more importantly, free the pointers appropriately.This might be acceptable, depending on your project, etc…
However, one usually uses some kind of smart-ptr in the vector (
vector<boost::shared_ptr<vehicle>>or Qt-something, or one of your own) that handles deallocation, but still permits storing different types objects in the same container.Update
Some people have, in other answers/comments, also mentioned
boost::ptr_vector. That works well as a container-of-ptr’s too, and solves the memory deallocation problem by owning all the contained elements. I prefervector<shared_ptr<T>>as I can then store objects all over the place, and move them using in and out of containers w/o issues. It’s a more generic usage model that I’ve found is easier for me and others to grasp, and applies better to a larger set of problems.