Webinar: Evaluation - 05.12
C and C++ are languages that have weak static typing. Static means that types are known at compile time, and weak means that languages enable different types to be mixed in the same expression and perform implicit conversions.
Despite the presence of implicit conversions, many operations require explicit type casting. To perform explicit type casting, special programming language constructs are used. They specify how to handle the type of a particular variable or expression.
Let's look at the main types of type casts in C and C++.
The const_cast operator is used in C++ to add or remove const and/or volatile qualifiers. Example:
const_cast<new_type>(expression)
The static_cast operator is used in C++ for type conversion at compile time. If the conversion fails, a compilation error is issued. General view:
static_cast<new_type>(expression)
The dynamic_cast conversion operator is used in C++ for polymorphic type conversion at runtime.
Example:
dynamic_cast<new_type>(expression)
If conversion is impossible, two scenarios can occur:
The reinterpret_cast operator is used in C++ to cast incompatible types based on their bit representation. For example, we can convert an integer to a pointer and vice versa. Example:
reinterpret_cast<new_type>(expression)
To cast an expression of any type to any other data type (with a few exceptions), use the C-style operator. Even though you can use it in C++, it is a bad practice since it becomes much easier to make a mistake. Example:
(new_type) expression
Sources
0