title: Heap corruption from structure inheritance
body: <p>I asked <a href="https://stackoverflow.com/questions/6512710/union-of-same-type-in-c">this question</a> yesterday which leads to today's question (indirectly). I was getting heap corruption with the following code:</p>
  
  <pre><code>typedef struct
  {
      void SetPos(const Vector2&amp; pos)
      {
          m_var1 = pos[0];
          m_var2 = pos[1];
      }
  
      Vector2 GetPos() const
      {
          return Vector2(m_var1, m_var2);
      }
  
      union
      {
          f32 m_var1;
          f32 m_var1DiffName;
      };
  
      union
      {
          f32 m_var2;
      };
  }StructBase;
  
  typedef struct Struct1 : public StructBase
  {
      Vec4f   m_foo;
  
  } Struct1;
  
  typedef struct Struct2 : public StructBase
  {
      Vector2   m_foofoo;
  
  } Struct2;
  
  typedef struct Struct3 : public StructBase
  {
      Struct3()
      {
          SetPos(Vector2(0, 0));
      }
  
      Struct3(const Vector2&amp; pos)
      {
          SetPos(pos);
      }
  } Struct3;
  </code></pre>
  
  <p>Every time I would add Struct3 to an Array (a Vector&lt;>), the debugger would break signalling heap corruption. If I turned off the heap-corruption detection, everything would work as expected, however Visual Studio would report heap corruption when shutting down the application. </p>
  
  <p>The change to Struct3 that fixed the problem: </p>
  
  <pre><code>typedef struct Struct3 : public StructBase
  {
  } Struct3;
  </code></pre>
  
  <p>Now my guess is that I was mixing a POD structure with a class disguised as a structure, but that seems like a long shot. What am I doing wrong here?</p>
  
  <p><strong>EDIT</strong>: The reason I added the constructors was so that I could add to a Vector&lt;> Struct3 by simply passing it a Vector3&lt;> which would construct the Struct3 and push it in to the array. So let's say the vector is: <code>vector&lt;Struct3&gt;</code> then I added Struct3's to it like so: <code>myVec.push_back(Vector2(i, j));</code> (the vector&lt;> is in a template class where the type can be any of these structures).</p>
  
  <p><strong>NOTE</strong>: I changed names around to avoid stepping on any NDA. So please ignore any style problems unless it actually affects the code. Since the code is rather simple, I pasted the whole thing, which I am sure many of you already know, is not possible all the time with production code. </p>