What is the diffrence between static_cast and dynamic_cast in RTTI

Dynamic_cast checks for datatype at runtime but static_cast checks at compilation. Is this the only diffrence b/w them or is there anything else? at the time of programming which shud we prefer to call.

Questions by vikaspachauri   answers by vikaspachauri

Showing Answers 1 - 9 of 9 Answers

static_cast
1)can do explicit conversion
2)can do implicit conversion ....to avoid warnings
3)can do unsafe down casting
4)can convert a integer in to some enum variable

.......it can't use run time information

2)dynamic_cast
only use to do typesafe downcasting
suppoce we have pointer of parent class that have the address of some child class
& we want to access the derive class exclusive member ..then we need to downcast it
if that pointer contain the address of child then it will downcast the pointer
otherwise it will retun NULL & if instead a pointer we have reference then it will through bad_typeid exception

ranjini_r

  • Jan 23rd, 2008
 

static_casts can be used to convert parent class to child class and vice - versa but the cast is an error for "unrelated classes".static casts can also be used to convert integral types to enum and vice-versa(enum can be converted to integral type cast without a type cast though).

the expression pChild = dynamic_cast<Child*>(pParent);
converts pointer pParent to type Child only if the pointed to object(i.e *pParent) is of
type Child or directly/indirectly derived from Child.The expression evaluates to null otherwise.Incase of references dynamic_cast throws bad_cast exception defined in typeinfo header file. Incase you want to call an uninherited method of the derived class during runtime,dynamic_cast is better as it will return null pointer if you cant safely assign the address of object to the pointer of Type Child.If you use
pChild = static_cast<Child*>(pParent); calling an uninherited method would be unsafe.I've never tried this though...

static_cast is used for all conversions that are well defined.
Like float to int. double to int etc.

dynamic_cast is used for type-safe downcasting. For this one must be working with a truly polymorphic hierarchy.(i.e with virtual functions).
downcasting is a method to convert the base class pointer to a derived class pointer.
incorrect downcast will produce a zero result.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions