Containers and virtual methods

One advantage of the virtual methods is to put objects related by a base class into a container; earlier, we saw a specific case of using a built-in array of base class pointers, but what about the Standard Library containers? As an example, imagine that you have a class hierarchy where there is one base class, base, and three derived classes, derived1, derived2, and derived3, and each class implements a virtual method who, as used earlier. One attempt to put objects in a container may be as follows:

    derived1 d1;     derived2 d2;     derived3 d3;     vector<base> vec = { d1, d2, d3 };     for (auto b : vec) b.who();     cout << endl;

The problem is that the vector holds base objects, and so as the items in the initialization ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.