Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The code you wrote is perfectly valid. There's nothing wrong with it (aside from the fact that <code>Derived::a</code> is private). It is well-formed and the behavior is defined (so far). As the quoted portion of the standard says, it is perfectly legal to upcast member pointers using an explicit <code>static_cast</code>, which is exactly what you are doing. 5.2.9/9 never says that the pointed member has to be present in the base class.</p> <p>Also, as you correctly quoted from the standard, the presence of the actual member in the object is required <em>later</em> at the moment of <em>dereference</em> of the pointer, not at the moment of initialization. This, of course, depends on the dynamic type of the object used at the left-hand side of member-access operator (<code>-&gt;*</code> or <code>.*</code>). The type is only known at run-time and thus cannot be checked by the compiler. </p> <p>This requirement is included as a mere note into 5.2.9/9, but it is reiterated in a more formal form in 5.5/4</p> <blockquote> <p>4 If the dynamic type of the object does not contain the member to which the pointer refers, the behavior is undefined.</p> </blockquote> <p>So, for example, in the context of your example the following lines of code are well-formed</p> <pre><code>Base b; b.*pa; // 1 Derived d; d.*pa; // 2 Base *pb = &amp;d; pb-&gt;*pa; // 3 </code></pre> <p>However, the first dereference produces undefined behavior (since object <code>b</code> does not contain the member), while both the second one and the third one are perfectly legal.</p>
    singulars
    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.
    3. 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