Viva64 Send comments on this topic.
Explicit type conversion

Glossary Item Box

C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. A cast, or explicit type conversion, is special programming instuction which specifies what data type to treat a variable as (or an intermediate calculation result) in a given expression. Casting will ignore extra information (but never adds information to the type being casted). The C/C++ cast is either "unchecked"* or "bit pattern"**. As an example with fundamental data types, a fixed-point float could be cast as an integer, where the data beyond the decimal (or binary) point is ignored.

There are two common casting styles, each outlined below.

C style casting:

(new_type)expression

C++ style casting:

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

_________________________________________

* "unchecked" - No check is perfomed and when the destination type can not hold the source value the result is undefined.
** "bit pattern" - The data is not interpreted at all and just the raw bit pattern is copied.

 

See also:

Converting Overview (MSDN); Type Conversion Tables (MSDN); Explicit conversion (MSDN); Usual Arithmetic Conversions (MSDN)