title: C++ How to properly copy container(vector) of pointers?
body: <p>A few times I've stumbled across the scenario where I have a container of pointers that needs to be copied.</p>
  
  <p>Let's say we have the following class hierarchy:</p>
  
  <ul>
  <li><p>Student (base class)</p>
  
  <ul>
  <li>Freshman (subclass)</li>
  <li>Sophmore (subclass)</li>
  <li>Junior (subclass)</li>
  <li>Senior (subclass)</li>
  </ul></li>
  <li><p>StudentService</p></li>
  </ul>
  
  <p>The StudentService class has a <code>std::vector&lt;Student*&gt; students</code> field and the following constructor:</p>
  
  <pre><code>StudentService::StudentService(std::vector&lt;Student*&gt; students) {
     // code
  }
  </code></pre>
  
  <p>It won't be correct to just use the <code>std::vector::operator=</code> operator and write <code>this-&gt;students = students</code>, because that will only copy the pointer addresses and so if someone from the outside deletes the objects pointed to by those pointers, then the StudentService class would suffer as a result.</p>
  
  <p>The solution is to loop through each pointer in the <code>students</code> parameter and create a new dynamic object, something like this:</p>
  
  <pre><code>for(int i = 0; i &lt; students.size(); i++) {
     this-&gt;students.at(i) = new Student(*students.at(i));
  }
  </code></pre>
  
  <p>But even that is not proper due to the fact that it will create ONLY Student objects. And we know that a Student can be a Freshman, Sophmore, Junior or Senior. So here is my question: what's the best solution to this problem?</p>
  
  <p>I guess one way would be to place a private enum field inside each Student class and have 4 if-else statements checking what type of Student it is and then creating a new dynamic object based on that like so:</p>
  
  <pre><code> for(int i = 0; i &lt; students.size(); i++) {
     if(students.at(i).getType() == FRESHMAN) {
        this-&gt;students.at(i) = new Freshman(*students.at(i));
     } else if(students.at(i).getType() == SOPHMORE) {
        this-&gt;students.at(i) = new Sophmore(*students.at(i));
     } else if {
     // and so on...
     }
  }
  </code></pre>
  
  <p>But this still seems quite cumbersome, so what would you suggest?</p>