Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Type Casting: benefit of using explicit casts?

Tags:

c++

casting

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?

like image 567
tiboo Avatar asked Jun 24 '10 07:06

tiboo


People also ask

What is an explicit cast in C++?

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

What is type type casting in C?

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.

What is implicit type casting?

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 cast operator in C with example?

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:


2 Answers

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.

like image 144
Janick Bernet Avatar answered Sep 25 '22 10:09

Janick Bernet


Just as every other implicit thing, it may hide away logic that developer/reviewer didn't have in mind, masking away bugs.

like image 34
Pavel Radzivilovsky Avatar answered Sep 23 '22 10:09

Pavel Radzivilovsky