Type-Casting.

closed account (zb0S216C)
I have read about type-casting with these operators:
1
2
3
4
5
reinterpret_cast< TYPE-ID >( EXPRESSION );
dynamic_cast< TYPE-ID >( EXPRESSION );
static_cast< TYPE-ID >( EXPRESSION );
const_cast< TYPE-ID >( EXPRESSION );
( TYPE-ID )EXPRESSION;


I have read about theses on multiple sites( including this one ) and I still don't know when to use them or how to implement them. Any suggestions on how I should use these?
Last edited on
You should avoid const_cast and reinterpret_cast
dynamic_cast is useful when you have polymorphic classes and you want to access a feature present only on a derived class
static_cast or C-style cast to convert between basic types
static_cast is the c++ equivalent to the C-style cast:
(Type-Id) variable

dynamic_cast casts a variable of a supertype into a variable of a subtype. Can only be used with pointers and references, I guess the reason is obvious.

const_cast casts a type into a const type and vice versa.

reinterpret_cast basically changes the type of the variable without changing the bit sequence. Very unsafe, you'd better have a good reason when using that one.

In general you should avoid casts. If you use only your own code you should rarely ever come into a situation where casts are necessary, and if they look necessary you should check your design for faults first. There are situations in which they are useful though.
closed account (zb0S216C)
Thanks Bazzy and hanst99! I now understand what each type-casting operator does and how it's used.
I understand that reinterpret_cast changes the type of the variable without changing the bit sequence.
But can anyone explain how C-style cast works or how it's different?
I'm reading a book which uses reinterpret_cast in example programs but switches to C-style casting in similar situations in later examples without any explanation.
Both are used to read/write a class object to files and both are working well for me.
The difference is that static_cast does not check whether the output is valid and reinterpret_cast can only be used for pointers and references. If a class cannot be converted to a related class, reinterpret_cast returns a NULL pointer, whereas static_cast would produce an invalid output.
Topic archived. No new replies allowed.