![]() |
VOOZH | about |
static_cast is a C++ type casting operator used to perform explicit conversions between compatible types. It is commonly used for numeric conversions, user-defined conversions, inheritance-related casts, and conversions involving void*.
The Value of a: 3 The Value of b: 3
Explanation: The floating-point value 3.5 is explicitly converted to an integer. The fractional part is discarded during the conversion.
static_cast<destination_type>(expression)
where:
static_cast can be used in several scenarios:
Unlike C-style casts, static_cast rejects invalid conversions during compilation.
Output
error: invalid static_cast from type 'char*' to type 'int*'Explanation: static_cast does not allow conversion between unrelated pointer types, helping prevent unsafe type conversions.
static_cast can invoke constructors and conversion operators defined by a class.
10
Explanation: The conversion operator operator string() is invoked to convert the object into a string.
In inheritance hierarchies, static_cast can be used for conversions between related classes.
Upcasting: It converts a derived-class pointer to a base-class pointer.
Explanation: Since Derived publicly inherits from Base, the conversion is valid and performed safely at compile time.
Limitation with Private Inheritance
Compile-time Error
[Error] 'Base' is an inaccessible base of 'Derived'Explanation: static_cast respects access control rules. If the base class is inaccessible, the conversion is not allowed.
Note: For inheritance-based casts, the base class must be accessible, unambiguous, and non-virtual.
static_cast allows conversions between object pointers and void*.
10
Explanation: The address of an integer is first converted to void* and then converted back to its original type.
The static_cast operator provides a safer and more explicit way to perform type conversions in C++, helping improve code readability and type safety.
Despite being safer than C-style casts, static_cast has certain restrictions and cannot be used for all types of conversions.