what is type casting | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

what is type casting

20th Jun 2016, 10:37 AM
s.imtiyaz fazal
s.imtiyaz fazal - avatar
2 Answers
+ 1
Type casting is type conversion. There are different types of conversion depending on between what types you want to cast. * static_cast: checked conversion between types of similar nature (e.g. int and float) at compile time * dynamic_cast: a checked type conversion between pointers to classes at runtime * const_cast: let's you change the const modifier of a type at compile time * reinterpret_cast: unchecked conversion at compile time from an arbitrary type to another arbitrary type (the compiler does not check if this can be converted, it just interprets the same data in a new way); pls prevent the use of reinterpret_cast, if you can, as this can lead to really nasty problems. Nevertheless, this operator is mostly useful in programming on a low level, i.e. on hardware or almost on hardware. Some examples: // static_cast float a = 10; int b = static_cast<int>(a); // dynamic_cast class A {}; class B: public A {}; class C: public A {}; A* pca = new B(); B* pcb = dynamic_cast<B*>(pca); // ok C* pcc = dynamic_cast<C*>(pca); // exception, pca does not refer to a C, it refers to a B // const_cast const int c = 11; int &d = const_cast<int>(c); const float e = const_cast<const float>(a); // reinterpret_cast C* f = reinterpret_cast<C*>(a); // float -> C*, ouch :-) To be completely honest, there's a fifth cast operator which was the only one initially in C++, as it is taken from C++s predecessor C. This operator is equivalent to the reinterpret_cast operator. Example: C* f = (C*)a; // float -> C*, still ouch :-) Please don't use the C casting operator at all, as the above mentioned four operators can do every type conversion and restrict the conversion to a more specific purpose. This prevents some unintended effects and also states more explicitly what kind of conversion you actually want to do (makes it more readable).
20th Jun 2016, 12:00 PM
Stefan
Stefan - avatar
0
simply putting type casting is a method of converting data types like int to float float to double so as to get a proper value to our logical arithmetic operations
20th Jun 2016, 2:42 PM
Akshay Kakoriya
Akshay Kakoriya - avatar