Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The cast in effect here is a <code>static_cast&lt;Derived&amp;&gt;</code>, governed by the following rule (§5.2.9 Static cast):</p> <blockquote> <p>An lvalue of type "<em>cv1</em> <code>B</code>," where <code>B</code> is a class type, can be cast to type "reference to <em>cv2</em> <code>D</code>," where <code>D</code> is a class derived (Clause 10) from <code>B</code>, if a valid standard conversion from "pointer to <code>D</code>" to "pointer to B" exists (4.10), <em>cv2</em> is the same cv-qualification as, or greater cv-qualification than, <em>cv1</em>, and <code>B</code> is neither a virtual base class of <code>D</code> nor a base class of a virtual base class of <code>D</code>. The result has type "<em>cv2</em> <code>D</code>."</p> </blockquote> <p>The cast "pointer to <code>D</code>" to "pointer to <code>B</code>" is a valid standard conversion (§4.10):</p> <blockquote> <p>A prvalue of type "pointer to <em>cv</em> <code>D</code>", where <code>D</code> is a class type, can be converted to a prvalue of type "pointer to <em>cv</em> <code>B</code>", where <code>B</code> is a base class (Clause 10) of <code>D</code>.</p> </blockquote> <p>However, just because the cast works, doesn't mean it's okay to do. Note (§5.2.9):</p> <blockquote> <p>If the object of type "<em>cv1</em> <code>B</code>" is actually a subobject of an object of type <code>D</code>, the result refers to the enclosing object of type <code>D</code>. Otherwise, the result of the cast is undefined.</p> </blockquote> <p>So this code results in undefined behaviour. You <em>can</em> cast from a base class to any of its derived classes, but you only have define behaviour if it truly is an object of that derived type.</p> <p>So to answer the questions:</p> <ol> <li>It's a <code>static_cast&lt;Derived&amp;&gt;</code>.</li> <li>Yes, because that's what's happening.</li> <li>It doesn't work anyway because it results in undefined behaviour.</li> <li>I can't be certain what the point was here. I'd expect that it <em>might</em> continue to perform as expected if you don't use any <code>Derived</code> specific features inside <code>foo</code>. However, if that's the case, just take a <code>Base&amp;</code>.</li> </ol>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload