8

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

I have done a lot of googling to find about:

  1. why to use C++ casting operators over traditional C style casting operators?
  2. When to use C++ casting operators, some live examples?

The following is what I found:

  • Traditionally any C++ casting operators is used for better maintenance of your code (ie) we can easily find where casting is used in code by just searching for this complex notation (reinterpret_cast<) unlike C style casting operators.

Now let me brief state why and when for each of the C++ casting operators

static_cast:

Why use it over C style casting? static_cast is used to perform conversion between related types.

Examples :

 Class A {};
 Class B {};

 A* a = new A();
 B* b = static_cast<B*>(a); // Compiler error
 B* b1 = (A*)a;  // Works fine
 float f;
 int addr = (int)(&f); // Works fine
 int addr = static_cast<int>(&f);  // Compiler error

But I wanted to know a real use case of when to use above code?

reinterpret_cast :

reinterpret_cast casts pointers to unrelated types.

Examples:

 Class A {};
 Class B {};

 A* a = new A();
 B* b = reinterpret_cast<B*>(a); // Works fine
 B* b1 = (A*)a;  // Works fine
 float f;
 int addr = (int)(&f); // Works fine
 int addr = reinterpret_cast<int>(&f);  // Works fine


 int ai = 10;
 float af = 13.33;
 // Would depend on how floating point is stored in machine
 // int& since reinterpret_cast expects either the type or operand to be pointer or reference 
 int ki = reinterpret_cast<int&>(af); // ki would not be 13
 int kitemp = (int)af; // kitemp would be 13

 // The same reinterpret_cast behaviour can be achieved using this,
 int* in = (int*)(af);
 cout << (*in);

My question is how else is reinterpret_cast different from C style casting? I'm unable to find why to use it over traditional casting operators and also when to use it?

Another important example which makes these operators worse is:

   const unsigned int * p;
   (int*)p; // Would remove unsigned and const at one shot
   // Using C++ casting operators
   // Const_cast expects a pointer or a reference
   reinterpret_cast<int*>(const_cast<unsigned int* >(p));

Writing the above code to remove const and unsigned is much more complex in C++ casting? Then why do people use reinterpret_cast, const_cast or static_cast over tradional C casting operators?

I do understand about dynamic_cast used in case of polymorphic classes; again this operator too has an extra cost of RTTI.

Community
  • 1
  • 1
Rishi Mehta
  • 303
  • 2
  • 8
  • 2
    C++ casts are restricted versions of the C-style cast, which tries almost every cast until it finds one that works. You should use C++ style casts when you want a certain type of conversion to take place and for the compilation to fail if that type of conversion cannot happen, where C-style casts are for "just do it" casts. – Seth Carnegie Dec 26 '11 at 06:20
  • @Mat : From the link you suggested, I got to understand a lot. But i had a doubt in the following, how would you map an example of this sort to C style casting, float a =13.33 ; int b = reinterpret_cast(a); ... Please make me understand this – Rishi Mehta Dec 26 '11 at 07:28
  • @RishiMehta: I have no idea what that cast is supposed to _mean_. Why would you write such a "thing"? – Mat Dec 26 '11 at 08:43
  • It would give the bitwise value of size int of 13.33. It is also called the union hack.. For more details, refer http://www.devx.com/cplus/Article/35609/1954 – Rishi Mehta Dec 26 '11 at 08:48

3 Answers3

8

Google's C++ Style Guide gives some motivation for using the C++ style casts:

The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g.,(int)3.5) and sometimes you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them.

I like the C++ casts because they make what you're intending to do very explicit, allowing the compiler to catch incorrect usage.

For example, if you know you intend to only do a numeric conversion to an integer, static_cast will only compile when that numeric conversion makes sense. As you showed in your example code, the C style casts will perform a cast regardless of the validity.

The C++ casts are really just for better documentation of intentions, and compile-time protection against unintended usage.

  • Yeah.. The link is really worth learning... But could you help me with cases where it is really useful to use C++ cast .. – Rishi Mehta Dec 26 '11 at 06:57
  • I added a bit to my answer. Does that help? If you have further questions, I could give more exact examples. –  Dec 26 '11 at 07:12
0

It's bad practice to remove the const qualifier. You will probably end up writing to a variable or region of memory that you are not supposed to write to. So that invalidates that part of your question.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
0

From my memory, reinterpret_cast is pretty much the same thing as c style cast except i think if you have a const Thing you cant reinterpret_cast to noncost_other_thing (c stye lets you remove them which may not be intentional and is likely dangerous).

I only use c casting in my own projects because i have the luxury of being lazy and sometimes i dont be lazy. You are 'suppose' to use C++ style casting and other C++ features (ostream rather then file, no printfs, avoid memset and other unsafe functions, etc) when using C++. But most people just do whatever they want (and get the bugs because of it).

Typically if you know when to use dynamic_cast and static cast you'll be fine. I find reinterpret_cast not likely unless i am interfacing with C and need to work with void*. const_cast... i actually never use and hope i will never need to. And you 'should' use them always.

PS: Unrelated note. I actually throw exception and assert(0) on unimplemented things. If i dont handle a param and expect it to be a 0 i'll write an exception or assert to check that. When i debug/add more code i run into these instead of bugs and theres absolutely no mystery on why it happened :)