title: C++ sizeof custom class returning incorrect value?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member">Why isn’t sizeof for a struct equal to the sum of sizeof of each member?</a>  </p>
  </blockquote>
  
  
  
  <p>Given the following class, with no other data members:</p>
  
  <pre><code>typedef uint32_t id_t;
  typedef int64_t loc_t;
  
  class foo:
  {
  public:
      enum bar : uint8_t
      {
          BAR1,
          BAR2,
          BAR3
      };
  private:
      id_t id;
      loc_t  start;
      loc_t  stop;
      bar std;
  };
  </code></pre>
  
  <p>Can anyone explain why:</p>
  
  <blockquote>
    <p>sizeof( id_t ) returns 4...<br>
    sizeof( loc_t ) returns 8...<br>
    sizeof( bar ) returns 1...  </p>
    
    <p>4+(2*8)+1 = 21</p>
  </blockquote>
  
  <p>Yet:</p>
  
  <blockquote>
    <p>sizeof( foo ) returns 32?</p>
  </blockquote>
  
  <p>Removing the uint8_t requirement on the bar enum type only succeeds in making sizeof( bar ) return 4 (int)  while sizeof( foo ) still returns 32 when 24 would be properly byte aligned.</p>
  
  <p>EDIT: The why has been satisfactorily answered. I thank everyone who commented as each brought a different set of detail to the table.</p>
  
  <p>The fix I need is for being able to use sizeof() to create file location offsets. So that when I write a foo to a file in binary format I can find the location immediately following it if I am later given it's location.  I'll update here if I find an elegant solution.</p>