So if i have a heterogeneous collection of Car objects
Car* c = {truck, van, convertible}
If the collection of objects was random and I wanted to go through the collection with a for loop, how can I test for the specific object type?
So if i have a heterogeneous collection of Car objects
Car* c = {truck, van, convertible}
If the collection of objects was random and I wanted to go through the collection with a for loop, how can I test for the specific object type?
You would use a dynamic_cast
:
if (truck* truck_p = dynamic_cast<truck*>(car_p)) {
// car_p points at a truck
}
dynamic_cast
will check the dynamic type of the object being pointed to by car_p
and only allow the cast if it is a truck
. If it is not a truck
, it will give the null pointer value and therefore the if
condition will fail.
However, the need to test a dynamic type like this suggests bad code design. The whole point of polymorphism is that you can treat any of the derived objects as though it were a base object - there should be no need to test exactly which derived type it was. If you need to check the dynamic type of a Car
so that you can do some truck
-specific operation on it, then you shouldn't be throwing that truck
into a container of Car*
.
If you have to know the derived type then polymorphism isn't the right tool for the job. I would suggest using a boost::variant or equivalent to implement a visitor pattern.
Try looking at RTTI:
http://en.wikipedia.org/wiki/Run-time_type_information
It's Run Time Type Information. You could also add a member variable into each derived type stating what type it is, and use that to check.