Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In theory, the compiler can lay out base classes differently. C++03 §10 paragraph 5 says:</p> <blockquote> <p>A base class subobject might have a layout (3.7) different from the layout of a most derived object of the same type.</p> </blockquote> <p>As <a href="https://stackoverflow.com/questions/7113422/why-can-it-be-dangerous-to-use-this-pod-struct-as-a-base-class/7113474#7113474">StackedCrooked mentioned</a>, this might happen by the compiler adding padding to the end of the base class <code>A</code> when it exists as its own object, but the compiler might not add that padding when it's a base class. This would cause <code>A::clear()</code> to overwrite the first few bytes of the members of the subclass.</p> <p>However in practice, I have not been able to get this to happen with either GCC or Visual Studio 2008. Using this test:</p> <pre><code>struct A { void clear() { memset(this, 0, sizeof(A)); } int age; char type; }; struct B : public A { char x; }; int main(void) { B b; printf("%d %d %d\n", sizeof(A), sizeof(B), ((char*)&amp;b.x - (char*)&amp;b)); b.x = 3; b.clear(); printf("%d\n", b.x); return 0; } </code></pre> <p>And modifying <code>A</code>, <code>B</code>, or both to be 'packed' (with <a href="http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx" rel="nofollow noreferrer"><code>#pragma pack</code></a> in VS and <a href="http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Type-Attributes.html" rel="nofollow noreferrer"><code>__attribute__((packed))</code></a> in GCC), I couldn't get <code>b.x</code> to be overwritten in any case. Optimizations were enabled. The 3 values printed for the sizes/offsets were always 8/12/8, 8/9/8, or 5/6/5.</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. 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