Casting in C++

Thameera Senanayaka

Allion Technologies

Casting

  • Also called type conversion
  • Changing a value of one data type to another

Implicit conversions

int a = 5;
double b = a;

C-Style Casts

double d = 3.0;
int i = (int)d;

C-Style casts can be abused

  • You can change type of variable without much effort
  • Hard to identify where type casting is used
  • Doesn't work well with inheritance and polymorphism

C++-Style Casts

  • static_cast
  • const_cast
  • dynamic_cast
  • reinterpret_cast

static_cast

  • This is the general purpose cast
  • Can be used to reverse an implicit conversion
  • Performs no runtime checks
void func( void *data )
{
    Image *img = static_cast< Image* >( data );
    
    // ... 
}

const_cast

  • Used to remove const to a variable
  • No any other C++ cast can remove it
const char *name = "abc";

someFunction( const_cast< char* >( name ) );

dynamic_cast

  • Exclusively used for handling polymorphism
  • If it can't cast, it'll throw NULL at runtime
void func( Image *img )
{
    if( PngImage *png = dynamic_cast< PngImage* >( img ) )
    {
    }
    else if( JpgImage *jpg = dynamic_cast< JpgImage* >( img ) )
    {
    }
}

reinterpret_cast

  • The most dangerous cast
  • Turns one type directly into another
  • Disregards all kinds of type safety
  • Casting back to original type will yield the same value only if intermediate type has enough capacity
long val = 0x12345cafebabe;
char *charPtr = reinterpret_cast< char* >( &val );

for( int i = 0; i < sizeof( long ); ++i )
{
    std::cout << byteToHex( *charPtr ) << std::endl;
    charPtr++;
}

C-style cast order

  • const_cast
  • static_cast
  • static_cast, const_cast
  • reinterpret_cast
  • reinterpret_cast, const_cast

C-style casts are dangerous because they can turn into reinterpret_casts

Thank you!

Casting in C++

By Thameera

Casting in C++

  • 970