What are benefits of using these operators instead of implicit casting in c++?
dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
Why, where, in which situation we should use them? And is it true that they are rarely used in OOP?
Casts are used to convert objects of any scalar kind to or from the other scalar type. Explicit type casts are constrained by the same rules that determine the effects of implicit conversions. Additional restraints on casts could result from the actual sizes or representation of specific types
Type casting in C refers to converting one data type to some other data type using cast operator. The cast operator is used to transform a variable into a different data type temporarily. Implicit type conversion is done automatically by the compiler, without being specified by the user, when there is more than one data type in an expression.
Implicit type casting means conversion of data types without losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the values stored inside the variable. Implicit type conversion happens automatically when a value is copied to its compatible data type.
What is the cast operator in C? Cast operator is a data type present in between parenthesis after the equal (=) operator and before the source variable. Implicit Type Conversion or Implicit Type Casting in C:
From the list of casts you provided, the only one that makes sense to be used to supstitute an implicit cast is the static_cast.
dynamic_cast is used to downcast a superclass into its subclass. This cannot happen implicitly and is actually something that is not that rare in OOP. static_cast could be used in such a cast too, it is however more dangerous, as it does not check during run time that the downcast is valid.
The last cast, reinterpret_cast, should be used very carefully as it is the most dangerous of all. You can essentially cast anything into anything with that - but you as the programmer will have to make sure that such cast makes sense semantically, as you essentially turn off type checking by doing such cast.
Just as every other implicit thing, it may hide away logic that developer/reviewer didn't have in mind, masking away bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With