Creating containers of polymorphic types are classic solutions that have their own problems. One of which types must be polymorphic just to add them to the container is not a good reason. Another problem is the early and tight connection, which leads to more complicated maintenance and lack of flexibility, just to add them to the container is not a good reason. Fortunately, there are better alternatives in C ++.
The best solution would be to store functions, not the objects themselves in containers. A common reason why you want to put different types in the same container is to perform the same actions for all of them, for example, Sphere::Draw() or Plane::Draw() . What you can do is create a container for drawing and wash. For instance.
vector<function<void()>> drawings; Sphere s; Plane p; drawings.push_back(bind(s, &Sphere::Draw)); drawings.push_back(bind(p, &Plane::Draw)); for(auto I = drawings.begin(); I != drawings.end(); ++i) (*i)();
Thus, you avoided strong communication and other inheritance problems and got a more flexible, more general solution.
The above solution only works with C ++ 11 , since it requires std :: function ()
source share