C++ types of casting and why it is not a safe method?


types of casting

Casting in C or C++ means converting one data type to another.Suppose you want to convert integer type to float type then casting will be performed.You can perform casting for built-in data types or some other entity which we will discuss as we cover more chapters.Casting discuss here is just a basic idea a detail description will be given in chapter 2 where more topics of C included in C++ is covered.There are two types of perform Casting:

I)Implicit casting and
II)Explicit casting.
 

Implicit casting

This type of casting does not make use of any standard library function to convert the data type.In this method to cast a value simply assign one data type value to another.Look at the code below.

Code example :For C++ programmer

#include <iostream>

using namespace std ;

int main( )
{
float f=89.7658 ;
    int i=int(f) , ///Casting is performed
    ii=(int)f ; ///Casting is performed

/// or ii=f ; //also works fine :data type not mentioned

cout<< i << endl
    << ii << endl ;

cin.get() ;
return 0 ;
}

Output,

89   89

Code example :For C programmer

float f=89.7658 ;
    int i=int(f) , ///Casting is performed
    ii=(int)f ; ///Casting is performed

/// or ii=f ; //also works fine :data type not mentioned

printf( “%i %i” , i , ii );

Output,

89   89

Note the three method of casting employed in implicit casting.The first two method mentioned the type to which the data is converted whereas in the third method data type is not mentioned.Such method of casting is inherited directly from C and so it is also known as C type casting.


Explicit casting

Explicit casting make use of some standard functions to convert one type to another.There are four functions that can perform explicit casting:

a)static_cast
b)const_cast
c)reinterpret_cast and
d)dynamic_cast. (meant only for C++ user)
 
When to use each function and their differences will be discussed thoroughly in Chapter 2.
 
The implicit and explicit casting method is shown briefly below.
 
C++ casting method
Fig.-Casting method in C++





Why casting is not a safe method?

&nbp;
Look at the code below.
 

long long ll=234235356767 ;
int i=int (ll) ;

When long long variable ‘ll’ whose size is 8 bytes,is converted to int type whose size is 4 bytes it results in some loss of information.This is due to difference in the size of the two data types.But even when the data type size are the same and casting is performed some values is still lost,say converting float to int type (as shown in the Implicit casting type example) the value losses it’s accuracy utterly.Due to this reason and another reason explained in Chapter 8 casting must be avoided as much as possible.


Related Link

->Represent int and char in binary format.
 
->C++ String type and it’s differences with char type.