Using typeid to compare between derived classes

I have a vector of pointers to derived objects inserted by the user (so I assume that the correct term is "known only at runtime):

vector<Person *> vect; 

Derived classes are men and women. I want to iterate on a vector to select only the Woman objects and call the copyconstructor instance. I thought 3 solutions:

  • Use flag;
  • To use typeid
  • To insert a call into the copy constructor in the default constructor of Female, so each time the user creates it, automatically create a double.

I do not like the first option for many types of derived classes. I do not like the third option, because it will cause a relationship problem (The world knows that every woman, but a woman cannot know the world). So I have to use the second option: Example

 typeid(vect.at(i))==typeid(Female) 

Is this expression correct? Is there any other way to outline the problem?

+6
source share
4 answers

Having Male and Female inheritance from Person sounds like a really weird 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 make a copy of the female, which again seems strange, replace the last line as follows:

  females.push_back(new Female(*p)); // copy the pointee 
+7
source
 typeid(vect.at(i))==typeid(Female) 

incorrect 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, namely whether you really need polymorphism. I really don't understand your third option.

+3
source

Do not model gender with inheritance, but simply use a numbered type in Person . Then you can use transform or remove_copy_if or similarly to find the female specified objects.

+3
source

You can also use dynamic_cast for this. For example, this means that fp points to a woman when pp has a Female object, and null otherwise;

 Person *pp; Female *fp; // ... fp = dynamic_cast<Female *> (pp); if (fp) fp->DoFemaleThing(); else cout << "Cast from Person to Female pointer failed"; 
+1
source

Source: https://habr.com/ru/post/907435/


All Articles