You cannot handle this directly:
As you can see, when a class is abstract, you cannot initiate an object.
Even if the class is not abstract, you will not be able to put derived objects in the list due to a slicing problem.
The solution is to use pointers.
So, the first question is: who owns the pointer (is the ownerβs ability to remove it when its lifetime expires).
With std :: list <> the list took responsibility by creating a copy of the object and obtaining ownership of the copy. But the pointer destructor does nothing. You need to manually call delete on the pointer to activate the obejct destructor. Thus, std :: list <> is not a good option for holding pointers when it also needs to take responsibility.
Solution 1:
This works great because the list is out of scope, then all objects work fine. But this is not very useful for dynamically created objects (runtime).
Solution 2:
Boost provides a set of containers that handle pointers. You give ownership of the pointer to the container, and the object is destroyed using the container when the container leaves the area.
boost::ptr_list<Actor> actorList; actorList.push_back(new ActorD1); actorList.push_back(new ActorD2); actorList.push_back(new ActorD2);
source share