News & UpdatesProgrammingWeb programmingPartnersStore
Book Cover
Buy Now
Projects
Links

C++ Tutorial – 30 – Type Conversions I

Converting an expression from one type to another is known as type-conversion. This can be done either implicitly or explicitly.

Implicit conversions

An implicit conversion is performed automatically by the compiler when an expression needs to be converted into one of its compatible types. For example, any conversions between the primitive data types can be done implicitly.

long a = 5;   // int implicitly converted to long
double b = a; // long implicitly converted to double

These implicit primitive conversions can be further grouped into two kinds: promotion and demotion. Promotion occurs when an expression gets implicitly converted into a larger type and demotion occurs when converting an expression to a smaller type. Because a demotion can result in the loss of information, these conversions will generate a warning on most compilers. If the potential information loss is intentional, the warning can be suppressed by using an explicit cast.

// Promotion
long   a = 5;  // int promoted to long
double b = a;  // long promoted to double
 
// Demotion
int  c = 10.5; // warning: possible loss of data
bool d = c;    // warning: possible loss of data

Explicit conversions

The first explicit cast is the one inherited from C, commonly called the C-style cast. The desired data type is simply placed in parentheses to the left of the expression that needs to be converted.

int  c = (int)10.5; // double demoted to int
char d = (char)c;   // int demoted to char

C++ casts

The C-style cast is suitable for most conversions between the primitive data types. However, when it comes to conversions between classes and pointers it can be too powerful. In order to get greater control over the different types of conversions possible C++ introduced four new casts, called named casts or new-style casts. These casts are: static, reinterpret, const and dynamic cast.

static_cast<new_type> (expression) 
reinterpret_cast<new_type> (expression) 
const_cast<new_type> (expression) 
dynamic_cast<new_type> (expression)

As seen above, their format is to follow the cast’s name with the new type enclosed in angle brackets and thereafter the expression to be converted in parentheses. These casts allow more precise control over how a conversion should be performed, which in turn makes it easier for the compiler to catch conversion errors. In contrast, the C-style cast includes the static, reinterpret and const cast in one operation. That cast is therefore more likely to execute subtle conversion errors if used incorrectly.

If you like this tutorial please +1 it:


One Response

Owen Lale
September 4th, 2011 at 14:38  

This content is a masterpiece. you’ve performed a magnificent task on this subject!

Leave a Reply