Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type casting [duplicate]

Tags:

c++

casting

Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?

Until a few days ago, I've always used C style type casting in C++ because it seemed to work good. I recently found out that using C in C++ is very bad..

I've never really used C++ casting before, so I'm wondering if someone could tell me (in their own words preferably) what the difference between static_cast, reinterpret_cast and const_cast are?

const_cast I know removes a "const" from something, but I'm not sure what the difference between them all is, and what one I need to use in different situations.

like image 766
Brad Avatar asked Jul 19 '10 04:07

Brad


People also ask

What is C type casting?

Type Casting is basically a process in C in which we change a variable belonging to one data type to another one. In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do.

Can C static cast?

Static casts are only available in C++. Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types.

Can you cast int to char in C?

In traditional C you can do: int i = 48; char c = (char)i; //Now c holds the value of 48. //(Of course if i > 255 then c will not hold the same value as i).

What is casting explain the type conversion?

In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type conversion, a data type is converted into another data type by a compiler. 2. Type casting can be applied to compatible data types as well as incompatible data types.


2 Answers

To say "C casting is bad" is an extremity that by itself is about as bad as using C-style casts all the time.

The areas where "new" C++ style casts should be used are: hierarchical casts (upcasts, downcasts, crosscasts), const-correctness casts and reinterpretation casts. For arithmetical casts C-style casts work perfectly fine and pose no danger, which is why they can safely be used in C++ code. In fact, I would actually recommend using specifically C-style casts as arithmetical casts - just to make arithmetical casts to look different from other cast types.

like image 176
AnT Avatar answered Nov 09 '22 22:11

AnT


  1. static_cast is the standard c++ way to do a cast at compile time when programmer knows the type of an object and/or wants to let the compiler know.
  2. dynamic_cast is like '(T)obj' where the cast is checked at runtime.
  3. reinterpret_cast is used to cast between different objects without a runtime check.
  4. const_cast explicitly converts to a type that is identical by removing the const and volatile qualifiers.
like image 30
josh Avatar answered Nov 09 '22 23:11

josh