Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of typeid to make a comparison between derived classes

Tags:

c++

types

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:

  1. To use a flag;
  2. To use typeid
  3. To insert a calling to the copy constructor in the default constructor of Female so every time the user creates one, automatically create the twin.

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?

like image 661
Ale Avatar asked Feb 01 '12 20:02

Ale


2 Answers

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
like image 117
fredoverflow Avatar answered Sep 23 '22 01:09

fredoverflow


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.

like image 40
Fred Foo Avatar answered Sep 23 '22 01:09

Fred Foo