A few times I've stumbled across the scenario where I have a container of pointers that needs to be copied.
Let's say we have the following class hierarchy:
Student (base class)
- Freshman (subclass)
- Sophmore (subclass)
- Junior (subclass)
- Senior (subclass)
StudentService
The StudentService class has a std::vector<Student*> students
field and the following constructor:
StudentService::StudentService(std::vector<Student*> students) {
// code
}
It won't be correct to just use the std::vector::operator=
operator and write this->students = students
, 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.
The solution is to loop through each pointer in the students
parameter and create a new dynamic object, something like this:
for(int i = 0; i < students.size(); i++) {
this->students.at(i) = new Student(*students.at(i));
}
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?
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:
for(int i = 0; i < students.size(); i++) {
if(students.at(i).getType() == FRESHMAN) {
this->students.at(i) = new Freshman(*students.at(i));
} else if(students.at(i).getType() == SOPHMORE) {
this->students.at(i) = new Sophmore(*students.at(i));
} else if {
// and so on...
}
}
But this still seems quite cumbersome, so what would you suggest?
Freshman
from aStudent
pointer? That's the question you need to search on SO. – Perzanstd::shared_ptr
) to ensure objects stay alive even if one copy is destroyed. – Stipule