I have a base class with several classes extending it. I have some generic library utilities that creates a vector containing pointers to the base class so that any of the subclasses will work. How can I cast all of the elements of the vector to a specific child class?
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs = castAsDogs(animals);
}
My naive solution would look something like this:
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs;
vector<Animal*>::iterator iter;
for ( iter = animals.begin(); iter != animals.end(); ++iter ) {
dogs.push_back(dynamic_cast<Dog*>(*iter));
}
}