title: Accessing Members of Outer Class without Storing Pointer
body: <p><strong>PROBLEM:</strong></p>
  
  <p>I want to set up a system of elements, while at the same time keeping <strong>pairs</strong> of these elements that I want to <strong>access</strong> and <strong>modify</strong> easily <em>(add more)</em>. </p>
  
  <p>At the same time, I want to <strong>keep the complexity to a minimum</strong>, and not implement everything in one class.</p>
  
  <p>I decided to store the indices to the pairs using a struct, which can handle a large amount of the complexity of calculations among B's.</p>
  
  <pre><code>class A {
      class B_pair {
          int idx_of_B[2];
  
      public:
          B get_B_value_1(); // how to access B's?
          B get_B_value_2();
          // a lot more member functions
      };
  
  public:
      std::vector&lt;B&gt;  B_values;
      std::vector&lt;B_pair&gt;  special_B_pairs;
      // a lot more stuff
  };
  </code></pre>
  
  <p>However, I have the problem that I cannot access the B values from within the B_pair class. </p>
  
  <p><strong>FAILED SOLUTION 1</strong></p>
  
  <pre><code>class A {
      A() { B_pair::outer = this; }
      class B_pair {
          static A *outer;
          void init_outer(A *o);
      };
  }
  </code></pre>
  
  <p>I used a <code>static</code> member because I have a lot of <code>B_pair</code> objects, and the <strong>extra memory of a pointer/reference in each is significant</strong>.</p>
  
  <p>This works fine. However, if I have more than one A objects at the same time, then it is problematic, as the <code>outer</code> pointer ends up pointing at the last created <code>A</code> object.</p>
  
  <p><strong>FAILED SOLUTION 2</strong></p>
  
  <p>Another approach I took was storing <strong>pointers</strong>.</p>
  
  <pre><code>class A {
      class B_pair {
          B *items[2];
      };
      std::list&lt;B&gt;  B_values; // I need random access iterators!!
  };
  </code></pre>
  
  <p>However, this means that I need to use more inefficient data structures than <code>std::vector</code>, which invalidates its iterators when it expands.</p>
  
  <p><strong>QUESTION</strong></p>
  
  <p>How could I access the members of the outer <code>class A</code> from the inner <code>class B</code>, or something similar to make this work? Ideally, I would like something similar to the first solution, but with one instance of <code>A *outer</code> for each <code>A</code> object.</p>
  
  <p>Note that <a href="https://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object">THIS IS POSSIBLE IN JAVA</a>!!</p>
  
  <p><strong>P.S.</strong> At the moment I am using the Singleton design pattern, and kept the static pointer. Not a big fan of this solution.</p>