When we use a container to store objects from an inheritance hierarchy, we generally must store those objects indirectly. We cannot put objects of types related by inheritance directly into a container, because there is no way to define a container that holds elements of differing types.
As an example, assume we want to define a vector
to hold several books that a customer wants to buy. It should be easy to see that we can’t use a vector
that holds Bulk_quote
objects. We can’t convert Quote
objects to Bulk_quote
(§15.2.3, p. 602), so we wouldn’t be able to put Quote
objects into that vector
.
It may be somewhat less obvious that we also can’t use a vector
that holds objects of type Quote
. In this case, we can put Bulk_quote
objects into the container. However, those objects would no longer be Bulk_quote
objects:
vector<Quote> basket;
basket.push_back(Quote("0-201-82470-1", 50));
// ok, but copies only the Quote part of the object into basket
basket.push_back(Bulk_quote("0-201-54848-8", 50, 10, .25));
// calls version defined by Quote, prints 750, i.e., 15 * $50
cout << basket.back().net_price(15) << endl;
The elements in basket
are Quote
objects. When we add a Bulk_quote
object to the vector
its derived part is ignored (§15.2.3, p. 603).