Above answers are good, conceptually you can think like this,
Your Car
object which is derived from Vehicle
class. You can refer Car
as Vehicle
, and can convert to Car
as it originally belonged to Car
. But it will be a problem if your Vehicle
object actually representing Bike
and trying to convert to Car
. Thats why you need safe casting.
class Vehicle
{
...
};
class Car : public Vehicle
{
...
};
class Bike : public Vehicle
{
...
};
int main(int argc, char const *argv[])
{
Vehicle* vehicle = new Car();
Car* old_car = dynamic_cast(vehicle);
if(old_car) {
// OK Vehicle is Car, use it
}
vehicle = new Bike();
old_car = dynamic_cast(vehicle);
if(old_car) {
// No Vehicle isn't Car, this code won't execute
}
return 0;
}