Storing objects in heterogeneous vector with stack-allocated objects
Hello,
Say I have an abstract class CA, derived into CA1, CA2, and maybe others.
I want to put objects of these derived types into a vector, that I embbed into a class CB. To get polymorphism right, I need to store a vector of pointers:
class CB
{
std::vector <CA*> v;
};
Now, say I have the following main function:
int main()
{
CB b;
CA1 a1;
CA2 a2;
b.Store( a1 );
b.Store( a2 );
}
How do I write the method void CB::Store(const CA&) in a simple way, so the stored objects survive when the original objects gets destroyed (which doesn't occur in the simple example above).
My problem is that I need to first copy objects on the heap before copying their adress in the vector, but how can I create an object of a derived type ? Sure, I could use RTTI, and search for all possible types, create and allocate a pointer, and copy (with proper casting) the object into the allocated space before pushing it into the vector. But this seems quite complicated, no ?
Is there a simpler way ?
(And without using dynamic allocation in the main !)