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.
As others has noted, you should neither use the
typeid, nor thedynamic_castoperator 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**ityou will get anAnimal&):Note you can apply the
typeidoperator 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 liketypeid(*it). Using it like that will give you justtypeid(Animal*)which isn’t useful.Similar,
dynamic_castcan be used:Note that in both cases, your Animal type should be polymorph. That means it must have or inherited at least one virtual function.