title: Using pointer arithmetic to iterate over class data members in C++
body: <p>I have a C++ class containing a bunch of data members of the same type and I want to iterate over them:</p>
  
  <pre><code>// C.h
  
  class C {
  
    // other members
  
    double foo;
    double bar;
    ...
    double barf; // 57th double declared since foo, nothing else in between
  
    // other members
  };
  </code></pre>
  
  <p>Pointer arithmetic seems to work, e.g. here using the constructor to initialize those 58 member doubles:</p>
  
  <pre><code>// C.cpp
  
  C::C() {
    for (int i = 0; i &lt; 58; i++) {
      *(&amp;this-&gt;foo + i) = 0;
    }
  }
  </code></pre>
  
  <p>I found related questions here <a href="https://stackoverflow.com/questions/15075947/how-to-iterate-through-variable-members-of-a-class-c">How to iterate through variable members of a class C++</a>, here <a href="https://stackoverflow.com/questions/7142532/c-iterating-through-all-of-an-objects-members">C++: Iterating through all of an object&#39;s members?</a>, here <a href="https://stackoverflow.com/questions/15430848/are-class-members-garaunteed-to-be-contiguous-in-memory">Are class members garaunteed to be contiguous in memory?</a> and here <a href="https://stackoverflow.com/questions/4177346/class-contiguous-data">Class contiguous data</a>, with some people suggesting this kind of thing is ok and others a no-no. The latter say there's no guarantee it won't fail, but don't cite any instances of it actually failing. So my question is, does anyone else use this, or has tried and got into trouble?</p>
  
  <p>Or maybe there's a better way? Originally in my application I did actually use an array instead to represent my object, with indices like so:</p>
  
  <pre><code>int i_foo = 0, i_bar = 1, ..., i_barf = 57;
  </code></pre>
  
  <p>However once I introduced different objects (and arrays thereof) the index naming started to get out of hand. Plus I wanted to learn about classes and I'm hoping some of the other functionality will prove useful down the line ;-)</p>
  
  <p>I use the iteration pretty heavily, e.g. to calculate statistics for collections of objects. Of course I could create a function to map the class members to an array one-by-one, but performance is a priority. I'm developing this application for myself to use on Windows with VS. I would like to keep other platform options open, but it's not something I intend to distribute widely. Thanks</p>