Monday, December 14, 2009

Casting : Static , Dynamic, Reinterpret and Const cast

1) dynamic_cast :
  • It has a Run-time check Based on Run-Time Type Information (RTTI) Information type_info to keep track of dynamic types.Quite heavy ...
  • It  ensures that Result object will have all valid Data.
Upcast  : cast of Derived object to base Object is Allowed .
Downcast : cast of Base object to Derived Object is Not Allowed .
  • When dynamic_cast cannot cast a pointer because it is not a complete object of the required class it returns a null pointer to indicate the failure.
  • If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown . As NULL assignment for Reference is not possible .

PS : It is Applicable only for Polymorphic classes.

Q  : What will happen when dynamic_cast is applied to a null pointer?
Ans :  It throws bad_typeid exception.


Q Where is  type_info (RTTI) is saved 
Ans VTABLE has a pointer (at begining ) pointing to type_info struct

2) Static_cast :
Wider than Dynamic (b2d : base to Derived , d2b : Derived to Base)
allows all d2b and b2d both Only condition is Pointer should be compatible type .
Pragremmer has to ensure result if b2d case if Pointer is Derefrenced ????

3) reinterpret_cast:
More wider than Static_cast :
anything to anything cast is allowed . Just do a memcpy bit by bit .
two reinterpret_cast s yields to same object as it was .

4) const_cast :
It changes the constness. Can remove or add constness for a variable .If we have to pass a const variable in Function who expects non-const  it can be used. To make it mutable

Example :

OUTPUT:
./a.out
Null pointer on second base to der DOWNCAST

1 comment:

Followers