title: Casting "Stylee"
body: <p>From the book Exceptional C++ Solution to ch. 44 I've learned that they are situations when none of the new cast styles would work properly. I always thought that they (those 4 new casts) cover every possible situation and there is no need for "old" style cast anymore, but it appears to be not true. So my question is:<br>
  Are those new casts cover all possible situations so there is no need to ever use c-style cast or:<br>
  There are situation in which only the old cast works properly?<br>
  Thanks.  </p>
  
  <p>That's appropriate fragment from this book:<br>
  "</p>
  
  <pre><code>class  A { public: virtual ~A(); /*...*/ }; 
  A::~A() { }
  
  class B : private virtual A  { /*...*/ };
  
  class C : public  A          { /*...*/ };
  
  class D : public B, public C { /*...*/ };
  
  A a1; B b1; C c1; D d1;
  const A  a2;
  const A&amp; ra1 = a1;
  const A&amp; ra2 = a2;
  char c;
  
  
      void f() 
  {
    A* pa; B* pb; C* pc;
    pa = (A*)&amp;ra1;
    pa = (A*)&amp;a2;&lt;&lt;----------This is the cast I'm interested in
  //This cannot be expressed as a new-style cast. The closest candidate is const_cast,  
   //but because a2 is a const object, the results of using the pointer are undefined.
  //Not my words those are words of Herb Sutter. (whose style of writing irritates me to bits)  
    pb = (B*)&amp;c1;
    pc = (C*)&amp;d1;
  }
  
  
  
  "
  </code></pre>
  
  <p><strong>EDITED</strong>  </p>
  
  <h2>Chapter 44 from Exceptional C++:</h2>
  
  <h3>"Item 44. Casts</h3>
  
  <p>Difficulty: 6</p>
  
  <p>How well do you know C++'s casts? Using them well can greatly improve the reliability of your code.</p>
  
  <p>The new-style casts in standard C++ offer more power and safety than the old-style (C-style) casts. How well do you know them? The rest of this problem uses the following classes and global variables:</p>
  
  <pre><code>class  A { public: virtual ~A(); /*...*/ }; 
  A::~A() { }
  
  class B : private virtual A  { /*...*/ };
  
  class C : public  A          { /*...*/ };
  
  class D : public B, public C { /*...*/ };
  
  A a1; B b1; C c1; D d1;
  const A  a2;
  const A&amp; ra1 = a1;
  const A&amp; ra2 = a2;
  char c;
  </code></pre>
  
  <p>This Item presents four questions.</p>
  
  <p>Which of the following new-style casts are not equivalent to a C-style cast?</p>
  
  <ul>
  <li>const_cast </li>
  <li>dynamic_cast</li>
  <li>reinterpret_cast</li>
  <li>static_cast</li>
  </ul>
  
  <p>For each of the following C-style casts, write the equivalent new-style cast. Which are incorrect if not written as a new-style cast?</p>
  
  <pre><code>void f() 
  {
    A* pa; B* pb; C* pc;
    pa = (A*)&amp;ra1;
    pa = (A*)&amp;a2;
    pb = (B*)&amp;c1;
    pc = (C*)&amp;d1;
  }
  </code></pre>
  
  <p>Critique each of the following C++ casts for style and correctness.</p>
  
  <pre><code>void g() 
  {
    unsigned char* puc = static_cast&lt;unsigned char*&gt;(&amp;c);
    signed char* psc = static_cast&lt;signed char*&gt;(&amp;c);
  
    void* pv = static_cast&lt;void*&gt;(&amp;b1);
    B* pb1 = static_cast&lt;B*&gt;(pv);
  
    B* pb2 = static_cast&lt;B*&gt;(&amp;b1);
  
    A* pa1 = const_cast&lt;A*&gt;(&amp;ra1);
    A* pa2 = const_cast&lt;A*&gt;(&amp;ra2);
  
    B* pb3 = dynamic_cast&lt;B*&gt;(&amp;c1);
  
    A* pa3 = dynamic_cast&lt;A*&gt;(&amp;b1);
  
    B* pb4 = static_cast&lt;B*&gt;(&amp;d1);
  
    D* pd = static_cast&lt;D*&gt;(pb4);
  
    pa1 = dynamic_cast&lt;A*&gt;(pb2);
    pa1 = dynamic_cast&lt;A*&gt;(pb4);
  
    C* pc1 = dynamic_cast&lt;C*&gt;(pb4);
    C&amp; rc1 = dynamic_cast&lt;C&amp;&gt;(*pb2);
  }
  </code></pre>
  
  <p>Why is it typically unuseful to const_cast from non-const to const? Demonstrate a valid example in which it can be useful to const_cast from non-const to const."</p>
  
  <h2><strong>Solution to chapter 44</strong></h2>
  
  <h3>Solution</h3>
  
  <p>Let's answer the questions one by one.</p>
  
  <p>Which of the following new-style casts are not equivalent to a C-style cast?</p>
  
  <p>Only dynamic_cast is not equivalent to a C-style cast. All other new-style casts have old-style equivalents.</p>
  
  <h2>Guideline</h2>
  
  <h3>Prefer new-style casts.</h3>
  
  <p><em>For each of the following C-style casts, write the equivalent new-style cast. Which are incorrect if not written as a new-style cast?</em></p>
  
  <pre><code>void f() 
  {
    A* pa; B* pb; C* pc;
    pa = (A*)&amp;ra1;
  </code></pre>
  
  <p>Use const_cast instead:</p>
  
  <pre><code>  pa = const_cast&lt;A*&gt;(&amp;ra1); 
  
    pa = (A*)&amp;a2;
  </code></pre>
  
  <p>This cannot be expressed as a new-style cast. The closest candidate is const_cast, but because a2 is a const object, the results of using the pointer are undefined.</p>
  
  <pre><code>  pb = (B*)&amp;c1; 
  </code></pre>
  
  <p>Use reinterpret_cast instead:</p>
  
  <pre><code>  pb = reinterpret_cast&lt;B*&gt;(&amp;c1); 
  
    pc = (C*)&amp;d1;
  </code></pre>
  
  <p>The above cast is wrong in C. In C++, no cast is required:</p>
  
  <pre><code>  pc = &amp;d1; 
  }
  </code></pre>
  
  <p><em>Critique each of the following C++ casts for style and correctness.</em></p>
  
  <p>First, a general note: All of the following dynamic_casts would be errors if the classes involved did not have virtual functions. Fortunately, A does provide a virtual function, making all the dynamic_casts legal.</p>
  
  <pre><code>void g() 
  {
    unsigned char* puc = static_cast&lt;unsigned char*&gt;(&amp;c);
    signed char* psc = static_cast&lt;signed char*&gt;(&amp;c);
  </code></pre>
  
  <p>Error: We must use reinterpret_cast for both cases. This might surprise you at first, but the reason is that char, signed char, and unsigned char are three distinct types. Even though there are implicit conversions between them, they are unrelated, so pointers to them are unrelated.</p>
  
  <pre><code>  void* pv  = static_cast&lt;void*&gt; (&amp;b1); 
    B*    pb1 = static_cast&lt;B*&gt;(pv);
  </code></pre>
  
  <p>These are both fine, but the first is unnecessary, because there is already an implicit conversion from a data pointer to a void*.</p>
  
  <pre><code>  B*    pb2 = static_cast&lt;B*&gt; (&amp;b1); 
  </code></pre>
  
  <p>This is fine, but unnecessary, since the argument is already a B*.</p>
  
  <pre><code>  A*    pa1 = const_cast&lt;A*&gt;(&amp;ra1); 
  </code></pre>
  
  <p>This is legal, but casting away const (or volatile) is usually indicative of poor style. Most of the cases in which you legitimately would want to remove the const-ness of a pointer or reference are related to class members and covered by the mutable keyword. See Item 43 for further discussion of const-correctness.</p>
  
  <h2>Guideline</h2>
  
  <h3>Avoid casting away const. Use mutable instead.</h3>
  
  <pre><code>  A*    pa2 = const_cast&lt;A*&gt;(&amp;ra2); 
  </code></pre>
  
  <p>Error: This will produce undefined behavior if the pointer is used to write on the object, because a2 really is a const object. To see why this is a legitimate problem, consider that a compiler is allowed to see that a2 is created as a const object and use that information to store it in read-only memory as an optimization. Casting away const on such an object is obviously dangerous.</p>
  
  <h2>Guideline</h2>
  
  <h3>Avoid casting away const.</h3>
  
  <pre><code>  B*    pb3 = dynamic_cast&lt;B*&gt;(&amp;c1); 
  </code></pre>
  
  <p>Potential error (if you try to use pb3): Because c1 IS-NOT-A B (because C is not publicly derived from B—in fact, it is not derived from B at all), this will set pb3 to null. The only legal cast would be a reinterpret_cast, and using that is almost always evil.</p>
  
  <pre><code>  A*    pa3 = dynamic_cast&lt;A*&gt;(&amp;b1); 
  </code></pre>
  
  <p>Probable error: Because b1 IS-NOT-AN A (because B is not publicly derived from A; its derivation is private), this is illegal unless g() is a friend of B.</p>
  
  <pre><code>  B*    pb4 = static_cast&lt;B*&gt;(&amp;d1); 
  </code></pre>
  
  <p>This is fine, but unnecessary because derived-to-public-base pointer conversions can be done implicitly.</p>
  
  <pre><code>  D*    pd = static_cast&lt;D*&gt;(pb4); 
  </code></pre>
  
  <p>This is fine, which may surprise you if you expected this to require a dynamic_cast. The reason is that downcasts can be static when the target is known, but beware: You are telling the compiler that you know for a fact that what is being pointed to really is of that type. If you are wrong, then the cast cannot inform you of the problem (as could dynamic_cast, which would return a null pointer if the cast failed) and, at best, you will get spurious run-time errors and/or program crashes.</p>
  
  <h2>Guideline</h2>
  
  <h3>Avoid downcasts.</h3>
  
  <pre><code>  pa1 = dynamic_cast&lt;A*&gt;(pb2); 
    pa1 = dynamic_cast&lt;A*&gt;(pb4);
  </code></pre>
  
  <p>These two look very similar. Both attempt to use dynamic_cast to convert a B* into an A*. However, the first is an error, while the second is not.</p>
  
  <p>Here's the reason: As noted above, you cannot use dynamic_cast to cast a pointer to what really is a B object (and here pb2 points to the object b1) into an A object, because B inherits privately, not publicly, from A. However, the second cast succeeds because pb4 points to the object d1, and D does have A as an indirect public base class (through C), and dynamic_cast is able to cast across the inheritance hierarchy using the path B*  D*  C*  A*.</p>
  
  <pre><code>  C* pc1 = dynamic_cast&lt;C*&gt;(pb4); 
  </code></pre>
  
  <p>This, too, is fine for the same reason as the last: dynamic_cast can navigate the inheritance hierarchy and perform cross-casts, so this is legal and will succeed.</p>
  
  <pre><code>  C&amp; rc1 = dynamic_cast&lt;C&amp;&gt;(*pb2); 
  }
  </code></pre>
  
  <p>Finally, an "exceptional" error: Because *pb2 isn't really a C, dynamic_cast will throw a bad_cast exception to signal failure. Why? Well, dynamic_cast can and does return null if a pointer cast fails, but since there's no such thing as a null reference, it can't return a null reference if a reference cast fails. There's no way to signal such a failure to the client code besides throwing an exception, so that's what the standard bad_cast exception class is for.</p>
  
  <p>Why is it normally unuseful to const_cast from non-const to const?</p>
  
  <p>The first three questions included no examples of using const_cast to add const, for example, to convert a pointer to non-const to a pointer to const. After all, explicitly adding const is usually redundant—for example, it's already legal to assign a pointer to non-const to a pointer to const. Normally, we only need const_cast to do the reverse.</p>
  
  <p>And the last part of the question: Demonstrate a valid example where it can be useful to const_cast from non-const to const.</p>
  
  <p>There is at least one case in which you could usefully const_cast from non-const to const—to call a specific overloaded function or a specific version of a template. For example:</p>
  
  <pre><code>void f( T&amp; ); 
  void f( const T&amp; );
  template&lt;class T&gt; void g( T&amp; t )
  {
    f( t );                       // calls f(T&amp;)
    f( const_cast&lt;const T&amp;&gt;(t) ); // calls f(const T&amp;)
  }
  </code></pre>
  
  <p>Of course, in the case of choosing a specific version of a template, it's usually just easier to name it explicitly instead of forcing the right deduction. For example, to call the right version of a templated function h(), writing "h( t )" is preferable to writing "h( const_cast(t) )".</p>