Take the following C++ for example.
vector<Animal> listAnimal;
class Fish : Animal ...
class Mammal : Animal ...
class Bird : Animal ...
If I then add them all to the list, and then grab them off the list arbitrary I wont know which subclass I am dealing with. I in Java I could do getClass() or thefish instanceof Fish. How do I do this in C++?
You shouldn’t need to know what type of sub-class you’re dealing with. You’re not doing polymorphism right if you need to check the type of class you’re dealing with. The whole point of polymorphism is to reduce if’s and make your code a lot more flexible.
There are some cases where you need to know, and you can use RTTI for that. However I recommend not to, especially if you require a lot of performance (such as games or graphics programs).
Use the
typeidoperator to get information about a class, and to determine if a class is a specific type.For example:
Then use a
static_castto cast it down the hierarchy.Alternatively you can use a
dynamic_castwhich is much safer, but much slower than a typeid/static_cast. Like so:EDIT:
dynamic_castis slower simply because it has to do a little extra work than just testing if it’s a specific type and casting. i.e.dyanmic_castis not equivalent totypeid/static_cast, but it almost is.Imagine a hierarchy further than 2 levels deep, for example:
Let’s say that in the Cat class, a method specific to all Cats is called:
scratchTheLivingHellOutOfYou(). Let’s also say that: I have a list of Animals and I want to callscratchTheLivingHellOutOfYou()for every Cat in the list (this includes classes that derive from the class Cat). If thetypeidoperator andstatic_castis used, this would not achieve what is required, sincetypeidonly checks for the current type and does not care about the hierarchy. For this, you have to use adynamic_cast, since it will check if a class is derived from a base-class, and then cast up/down the hierarchy accordingly.You can see this simple example, in C++, here. Here is the output of the program:
Therefore, you can clearly see that
dynamic_castdoes a lot more work than a simpletypeidandstatic_cast. Sincedynamic_castlooks up the hierarchy to see if it is a specific type. Simply put…dynamic_castcan cast up and down the hierarchy. Whereas atypeidandstatic_castcan only cast down the hierarchy to a specific type.I thought I’d mention that if
dynamic_castfails it will return a NULL pointer, or throw an exception if you’re using it with references.NOTES:
dynamic_castshould only be used if you’re not sure the object will be the type you’re converting to. If you, as a programmer, know whatever you’re casting is 100% going to be that type then usestatic_cast, e.g. if you know animal1 is going to be aCatthenstatic_castis more appropriate.