Hi everyone.I've got a question on dynamic cast.Dynamic_cast allows us to downcast a data type from one to a more specific one in the same hierarchy.
But why not declare the variable we need to the appropriate type during programming time rather than downcasting it at run time?
I don't think that the developers of C++ included dymanic_cast by mistake or for the sake of commands redundancy... Then why? What's its additional use and benefits??

When you need it, you'll have your answers.

>But why not declare the variable we need to the appropriate type
>during programming time rather than downcasting it at run time?
Because that might not be practical. Consider an array of base class pointers with varying dynamic types down the hierarchy, but depending on the dynamic type, you need to call a member function that's not available to the base class. Polymorphism breaks down here, and you're stuck with a downcast. But because arrays must be heterogenous, you're also stuck with base class pointers. Enter RTTI and dynamic_cast to the rescue. It's not pretty, and it's not encouraged, but it works when you need it.

In addition to wat Narue said...

Given an instance of class C, there is a B subobject and an A subobject. The instance of C, including the A and B subobjects, is the "complete object."

Using run-time type information, it is possible to check whether a pointer actually points to a complete object and can be safely cast to point to another object in its hierarchy. The dynamic_cast operator can be used to make these types of casts. It also performs the run-time check necessary to make the operation safe.

Attachments ClassPic.JPG 2.51 KB

Hi ,
Could u please an example code ,so that it will be more understandable.
1) can u tel me a situation where i will have use dynamic cast only, otherwise it is not posiible,My point is i can achive the same by c style casting too...
haramohan sahu

I posted an example just a few minutes ago in this thread.

>>My point is i can achive the same by c style casting too...
Just change from static_cast<char*>(obj) // c++ style case
to (char *)obj; // c style case

This article has been dead for over six months. Start a new discussion instead.