C++ class identification question

I'll phrase this in the form of an example to make it more clear.

Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?

class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};

int main()
{
vector<Animal*> stuff;
//cramming the dogs and cats in...

for(/*all elements in stuff*/)
//Something to the effect of:  if(stuff[i].getClass()==Dog) {/*do something*/}

}

I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can.

Is there a way to do this? Thanks in advance.

Answers


As others has noted, you should neither use the typeid, nor the dynamic_cast operator to get the dynamic type of what your pointer points to. virtual functions were created to avoid this kind of nastiness.

Anyway here is what you do if you really want to do it (note that dereferencing an iterator will give you Animal* . So if you do **it you will get an Animal&):

for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
    if(typeid(**it) == typeid(Dog)) {
        // it's a dog
    } else if(typeid(**it) == typeid(Cat)) {
        // it's a cat
    }
}

Note you can apply the typeid operator to types itself too, as shown above. You don't need to create an object for this. Also note the typeid way doesn't work if you pass it a pointer like typeid(*it) . Using it like that will give you just typeid(Animal*) which isn't useful.

Similar, dynamic_cast can be used:

for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
    if(Dog * dog = dynamic_cast<Dog*>(*it)) {
        // it's a dog (or inherited from it). use the pointer
    } else if(Cat * cat = dynamic_cast<Cat*>(*it)) {
        // it's a cat (or inherited from it). use the pointer. 
    }
}

Note that in both cases, your Animal type should be polymorph. That means it must have or inherited at least one virtual function.


Need Your Help

JSON-LD document + Hydra Core generate Java code

java spring-mvc json-ld hydra-core

IS there a tool which generates skeleton for a RESTful service for JSON-LD which have operation defined using hydra. For instance take below example, assume I have a Java class present Person, what...

Sub menu wordpress toggle

javascript jquery wordpress

I want to toggle menu items that only have sub menu but what's happening right now is I'm not able to find a way to toggle a single menu item, whenever I toggle every parent menu item that has ch...