Polymorphism of virtual class hierarchies works only with the help of links or pointers in the base subobject:
struct Der : Base { }; Der x; Base & a = x; a.foo();
The function foo sent polymorphically if it is a virtual function in Base ; polymorphism refers to the fact that when calling a member function of an object of type Base function that is actually called can be implemented in the Der class.
Containers can only store items of a fixed type. To save a polymorphic collection, you can instead have a container of pointers to the base class. Since you need to store the actual objects elsewhere, lifecycle management is non-trivial and best left to a dedicated shell such as unique_ptr :
#include <list> #include <memory> int main() { std::list<std::unique_ptr<Base>> mylist; mylist.emplace_back(new Der1); mylist.emplace_back(new Der2); // ... for (p : mylist) { p->foo(); /* dispatched dynamically */ } }
Kerrek SB
source share