Ale
Ale

Reputation: 1199

use of typeid to make a comparison between derived classes

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?

Upvotes: 7

Views: 9463

Answers (4)

Michael Chinen
Michael Chinen

Reputation: 18697

You can also use dynamic_cast to do this. For example this makes fp point to a female in the case where pp holds 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";

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263118

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

Upvotes: 8

Mark B
Mark B

Reputation: 96241

Don't model gender with inheritance, but rather just use an enumerated type in Person. Then you can use transform or remove_copy_if or similar to find the female indicated objects.

Upvotes: 3

Fred Foo
Fred Foo

Reputation: 363567

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.

Upvotes: 3

Related Questions