I got a vector of pointers to a base class foo which got a couple of child classes and what I would like to do is based on which child class it is, create a new class of the same instance.
I’ve solved it earlier by having a gigantic for loop which uses typeid to find out what class it is but is there no way to solve it in a more general way?
Basically, something like this is what I’m looking for:
std::vector<foo*> a;
std::vector<foo*> b;
//Store a couple of classes in a and b
b[0] = new typeid(a[0]).name();
One approach is to have a virtual
clone()method that returns a pointer to an object of the right type:Then your code would be
In real life code you would return a smart pointer, e.g. an
std::unique_ptr<base>.