I have a vector of pointers to derived objects insert by the user (so I guess the correct term is "known only in runtime)::
vector<Person *> vect;
The derived classes are Male and Female. I want to make an iteration on the vector to select only the Female objects and call the copyconstructor of that. I thought 3 solutions:
I don't like the first option in the case of many kind of derived classes. I don't like the third option too because would cause a problem of relationship (the World knows every Female but the Female can't know the World). So I should use the second option: example
typeid(vect.at(i))==typeid(Female)
Is this expression correct? Is there another way to outline the problem?
Having Male
and Female
inherit from Person
sounds like a really strange design, but here we go:
vector<Person*> vect;
vector<Female*> females;
for (vector<Person*>::const_iterator it = vect.begin(); it != vect.end(); ++it)
{
if (Female* p = dynamic_cast<Female*>(*it))
{
females.push_back(p); // copy the pointer
}
}
If you really want to perform a copy of the female, which again sounds strange, replace the last line with:
females.push_back(new Female(*p)); // copy the pointee
typeid(vect.at(i))==typeid(Female)
is wrong if vect
contains pointers. You mean
typeid(*vect.at(i)) == typeid(Female))
Whether typeid
or a simple flag should be used depends on the architecture of your program, specifically on whether you really need polymorphism. I don't really understand your third option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With