Any tips/idioms on how to store polymorphic objects in STL containers in C++?
Example:
class B { ... };
class C : public B { ... };
class D : public B { ... };
In this scenario, I would like to make a vector containing a mix of B, C and D objects.
If I make a
vector<B>
, all objects would be of static type B so it wouldn't work, right? And if I make a
vector<B*>
, I need extra outside code for handling memory allocation/deallocation of B, C, and D objects, which ruins the whole idea of abstract data structures that encapsulate everything, unless I write a very complex wrapper or inherited version of vector.
Any ideas/standard ways for dealing with this kind of problem in an elegant, encapsulated way?