title: Creating c++ vector of pointers
body: <p>In my C++ code I have a class Object equipped with an id field of type int. Now I want to create a vector of pointers of type Object*. First I tried</p>
  
  <pre><code>vector&lt;Object*&gt; v;
  
  for(int id=0; id&lt;n; id++) {
      Object ob = Object(id);
      v.push_back(&amp;ob);
  }
  </code></pre>
  
  <p>but this failed because here the same address just repeats itself n times. If I used the new operator I  would get what I want but I'd like to avoid dynamic memory allocation. Then I thought that what I need is somehow to declare n different pointers before the for loop. Straightforward way to this is to declare an array so I did this :</p>
  
  <pre><code>vector&lt;Object*&gt; v;
  Object ar[n];
  
  for(int i=0; i&lt;n; i++) {
      ar[i] = Object(i);
  }
  
  for(int i=0; i&lt;n; i++) {
      v.push_back(ar+i);
  }
  </code></pre>
  
  <p>Is there still possibility to get a memory leak if I do it this way? Also going through an array declaration is a bit clumsy in my opinion. Are there any other ways to create vector of pointers but avoid manual memory management?</p>
  
  <p>EDIT: Why do I want pointers instead of just plain objects?</p>
  
  <p>Well I modified the original actual situation a bit because I thought in this way I can represent the question in the simplest possible form. Anyway I still think the question can be answered without knowing why I want a vector of pointers.</p>
  
  <p>Actually I have</p>
  
  <pre><code>Class A {
  protected:
      vector&lt;Superobject*&gt; vec;
  ...
  };
  
  Class B: public A {...};
  
  Class Superobject {
  protected:
      int id;
  ...
  }
  
  Class Object: public Superobject {...}
  </code></pre>
  
  <p>In derived class <code>B</code> I want to fill the member field <code>vec</code> with objects of type <code>Object</code>. If the superclass didn't use pointers I would have problems with object slicing. So in class <code>B</code> constructor I want to initialize <code>vec</code> as vector of pointers of type <code>Object*</code>.</p>
  
  <p>EDIT2</p>
  
  <p>Yes, it seems to me that dynamic allocation is the reasonable option and the idea to use an array is a bad idea. When the array goes out of scope, things will go wrong because the pointers in vector point to memory locations that don't necessarily contain the objects anymore. </p>
  
  <p>In constructor for class B I had</p>
  
  <pre><code>B(int n) {
      vector&lt;Object*&gt; vec;
      Object ar[n];
  
      for(int id=0; id&lt;n; id++) {
          ar[id] = Object(id);
      }
  
      for(int id=0; id&lt;n; id++) {
          v.push_back(ar+id);
      }
   }
  </code></pre>
  
  <p>This caused very strange behavior in objects of class B. </p>