dynamic_cast explained

dynamic_cast explained

Dynamic cast is a tool by which a we can explicitly instruct the compiler to perform type conversion at runtime. This is useful when type of an object is not known at compile time, but can be found at runtime.

Let us see this with an example,

int main()
{
    Vehicle* veh = new Car();
    Car* car = dynamic_cast<Car*>(veh);
    if (car != nullptr)
    {
        // The type of veh is Car, so we can call Car's member functions
        car->doSomething();
    }
    else
    {
        // veh is not of car type, so we can't call Car's member functions
    }
    delete veh;
    return 0;
}

In this example, we have a Vehicle class called Vehicle and a Car class called Car. We create a pointer to Vehicle called veh, and then use dynamic cast to convert it to a pointer to Car called car.

If the type of veh is actually Car, then the dynamic cast will succeed and car will point to a valid Car object. If not, dynamic_cast will return a nullptr