title: Vector elements in c++ always set to last element
body: <p>I want to store members of a class into a vector. In my class, I have some private variables that I access via constant pointers so that they are protected from being changed (<a href="https://stackoverflow.com/questions/5424042/class-variables-public-access-read-only-but-private-access-read-write">see this post</a>). Problem: When I add instances of the class into a vector during a loop and access them afterwards, all elements seem to be the last one added. Here's a MWE:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  class myClass {
  private:
      int x_;
  
      void init(int x) {
          x_ = x;
      }
  
  public:
      const int &amp;x;
  
      myClass(int x) : x(x_) {
          init(x);
      };
  };
  
  int main(int argc, const char * argv[]) {
      vector&lt;myClass&gt; myVector;
  
      // Does not work
      for (int j=0; j&lt;3; j++) {
          myVector.push_back(myClass(j));
      }
      for (int j=0; j&lt;3; j++) {
          cout &lt;&lt; "1st attempt: " &lt;&lt; myVector.at(j).x &lt;&lt; endl;
      }
      myVector.clear();
  
      // Works
      for (int j=0; j&lt;3; j++) {
          myVector.push_back(myClass(j));
          cout &lt;&lt; "2nd attempt: " &lt;&lt; myVector.at(j).x &lt;&lt; endl;
      }
      myVector.clear();
  
      // Works also
      myVector.push_back(myClass(0));
      myVector.push_back(myClass(1));
      myVector.push_back(myClass(2));
      for (int j=0; j&lt;3; j++) {
          cout &lt;&lt; "3rd attempt: " &lt;&lt; myVector.at(j).x &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Ovious question: What am I doing wrong and can I fix it?</p>