0

What are the type-casting types?

Ive seen static_cast, dynamic_cast or reinterpret_cast but i dont know the difference between them.

27th Jun 2016, 8:29 PM
Garme Kain
Garme Kain - avatar
6 ответов
+ 2
Hi Garme, the different cast operators do different types of conversion: * static_cast: checked conversion between types of similar nature (e.g. int and float) at compile time * dynamic_cast: a checked 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 you will ever need 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).
29th Jun 2016, 1:13 AM
Stefan
Stefan - avatar
0
I don't understand, why did you write int &d, what is the meaning of it?
22nd Jul 2016, 6:54 PM
Aceitunarabe
Aceitunarabe - avatar
0
&d means that d is an alias for the term on the right side of the equals sign. A bit of a stripped-down example : int a = 5; int &b = a;
22nd Jul 2016, 6:59 PM
Stefan
Stefan - avatar
0
Okok, I realize, I did not answer your question. :-) I did it to have some variety as the example is quite long. :-)
22nd Jul 2016, 7:00 PM
Stefan
Stefan - avatar
0
Ok thx!
22nd Jul 2016, 7:15 PM
Aceitunarabe
Aceitunarabe - avatar
0
My pleasure :-)
22nd Jul 2016, 7:17 PM
Stefan
Stefan - avatar