Thursday, November 19, 2009

C++ cast operators

Describe C++ cast operators

static_castis used to cast up and down the class hierarchy, conversions with unary constructors as well as conversions with conversion operators. It is similar to the C-style casts.

For instance, in the code below, a call is made to the operator int in class X

dynamic_cast is the C++ way of casting. It uses RTTI to determine if the cast is valid.

If we are attempting to cast to an incompatible pointer type, the result is a NULL.

If we try to cast to an incompatible reference type, an std::bad_cast exception is thrown.

The dynamic_cast must be un-ambigous.

dynamic_cast works only with polymorphic types (ie where the classes have at least one virtual function)

struct X
 {
     int value;
     virtual ~X() {}
 };

 struct Y : public X
 {
 };


 int main(int, char **)
 {
     Y anY;
     X anX;

     X & xRef = anY;
     Y& yRef = dynamic_cast( xRef );

     X& xRef2 = anX;
     try
     {
         Y& yRef2 = dynamic_cast( xRef2 );
     }
     catch( std::bad_cast&  e)
     {
         std::cout <<"Caught bad cast exception ! " << e.what() << "\n";
     }
     std::cout << "Program finished !\n";
     return 0;
 }


reinterpret_castAllows you to cast apples to horses.

const_castallows us to cast away the const or volatile from a reference or pointer. The target data type must be the same as the source type.