title: Linux kernel: why do 'subclass' structs put base class info at end?
body: <p>I was reading the chapter in <a href="http://shop.oreilly.com/product/9780596510046.do" rel="nofollow noreferrer">Beautiful Code</a> on the Linux kernel and the author discusses how Linux kernel implements inheritance in the C language (amongst other topics).  In a nutshell, a 'base' struct is defined and in order to inherit from it the 'subclass' struct places a copy of the base <strong>at the end</strong> of the subclass struct definition.  The author then spends a couple pages explaining a clever and complicated macro to figure out how many bytes to back in order to convert from the base part of the object to the subclass part of the object.</p>
  
  <p><strong>My question:</strong> Within the subclass struct, why not declare the base struct as the <em>first</em> thing in the struct, instead of the <em>last</em> thing?</p>
  
  <p>The main advantage of putting the base struct stuff first is when casting from the base to the subclass you wouldn't need to move the pointer at all - essentially, doing the cast just means telling the compiler to let your code use the 'extra' fields that the subclass struct has placed after the stuff that the base defines.</p>
  
  <p>Just to clarify my question a little bit let me throw some code out:</p>
  
  <pre><code>struct device { // this is the 'base class' struct
       int a;
       int b;
       //etc
  }
  struct usb_device { // this is the 'subclass' struct
      int usb_a;
      int usb_b;
      struct device dev; // This is what confuses me - 
                         // why put this here, rather than before usb_a?
  }
  </code></pre>
  
  <p>If one happens to have a pointer to the "dev" field inside of a usb_device object then in order to cast it back to that usb_device object one needs to subtract 8 from that pointer.  But if "dev" was the first thing in a usb_device casting the pointer wouldn't need to move the pointer at all.</p>
  
  <p>Any help on this would be greatly appreciated.  Even advice on where to find an answer would be appreciated - I'm not really sure how to Google for the architectural reason behind a decision like this.  The closest I could find here on StackOverflow is:
  <a href="https://stackoverflow.com/questions/16397192/why-to-use-these-weird-nesting-structure">why to use these weird nesting structure</a></p>
  
  <p>And, just to be clear - I understand that a lot of bright people have worked on the Linux kernel for a long time so clearly there's a good reason for doing it this way, I just can't figure out what it is.</p>