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*
.