Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The C code is not valid (nor would the equivalent C++ code in a context where the class definition is not visible) because what C does in this case is the equivalent of a <code>reinterpret_cast</code>. Note that in a simple situation like yours it will likely "work" because most compilers will put the single base object at the beginning of the derived object, so a pointer adjustment is not necessary. However, in the general case (especially when using multiple inheritance), the pointer will have to be adjusted to point to the correct subobject, and since C does not know how to do that, the cast is wrong.</p> <p>So what is meant with "pointer adjustment"? Consider the following situation:</p> <pre><code>class A { virtual ~A(); int i; ... }; class B { virtual ~B(); int j; ... }; class C: public A, public B { ... }; </code></pre> <p>Now the layout of <code>C</code> may be as follows:</p> <pre><code>+----------------------------+----------------------------+ | A subobject (containing i) | B subobject (containing j) | +----------------------------+----------------------------+ </code></pre> <p>where the virtual pointers of both the <code>A</code> and <code>B</code> subobjects point to <code>C</code>.</p> <p>Now imagine you've got a <code>C*</code> which you want to convert to a <code>B*</code>. Of course the code which receives the <code>B*</code> may not know about the existence of <code>C</code>; indeed, it may have been compiled before <code>C</code> was even written. Therefore the <code>B*</code> must point to the <code>B</code> subobject of the <code>C</code> object. In other words, on conversion from <code>C*</code> to <code>B*</code>, the size of the <code>A</code> subobject has to be added to the address stored into the pointer. If you do not do this, the <code>B*</code> will actually point to the <code>A</code> subobject, which clearly is wrong.</p> <p>Now without access to the class definition of <code>C</code>, there's of course no way to know that there even <em>is</em> an <code>A</code> subobject, not to mention how large it is. Therefore it is impossible to do a correct conversion from <code>C*</code> to <code>B*</code> if the class definition of <code>C</code> is not available.</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