title: Providing iterable "views" of a class by casting parent class to reference to child
body: <p>I have a class, and there are several ways to iterate over it. For example, you can iterate to see all the <code>A</code>'s, <code>B</code>'s, or <code>C</code>'s inside it. The class has no virtual functions.</p>
  
  <p>I want these to have a nice interface. I am wondering if the following gives undefined or unspecified behavior, or if it is OK to do.</p>
  
  <p>I am thinking about making three derived classes of this class:</p>
  
  <pre><code>// can look at this in three ways
  struct myClass {
      void myFunc();
  };
  
  struct A_view : public myClass {
      A_iterator begin();
  };
  
  struct B_view : public myClass {
      B_iterator begin();
  };
  
  
  struct C_view : public myClass {
      C_iterator begin();
  };
  </code></pre>
  
  <p>Then</p>
  
  <pre><code>A_view&amp; get_C_view(const myClass&amp; c) {
      return *reinterpret_cast&lt;B_view*&gt;(&amp;c);
  }
  
  B_view&amp; get_B_view(const myClass&amp; c) {
      return *reinterpret_cast&lt;B_view*&gt;(&amp;c);
  }
  
  C_view&amp; get_C_view(const myClass&amp; c) {
      return *static_cast&lt;C_view*&gt;(&amp;c);
  }
  </code></pre>
  
  <p>I want to be able to do use it like</p>
  
  <pre><code>myClass inst;
  
  for (auto&amp; c : get_C_view(inst))
      //stuff
  
  for (auto&amp; b : get_B_view(inst))
      //stuff
  </code></pre>
  
  <p>and</p>
  
  <pre><code>auto&amp; bview  = get_b_view(inst);
  
  std::transform(bview.begin(), bview.end(), bview.begin(), [](auto&amp; x, auto&amp; y) { /* smthing */ });
  
  bview.myFunc();
  </code></pre>
  
  <p>or whatever with the algorithms from <code>&lt;algorithm&gt;</code>. As you can see, you can also use the functions defined in the parent class on the view.</p>
  
  <p>So, I am casting an instance to a reference to a type that is derived from it which adds only functions, not data, but it is not actually one of those types.</p>
  
  <p>Is this ok? By "ok" I mean</p>
  
  <ol>
  <li>Is this well defined, undefined, or unspecified behavior?</li>
  <li>If not well defined, will this cause problems in practice?</li>
  <li>Would Herb Sutter frown upon it?</li>
  </ol>