Put (Smart) Pointers, Not Objects, in Containers

When we need a container that holds objects related by inheritance, we typically define the container to hold pointers (preferably smart pointers (§12.1, p. 450)) to the base class. As usual, the dynamic type of the object to which those pointers point might be the base-class type or a type derived from that base:

vector<shared_ptr<Quote>> basket;basket.push_back(make_shared<Quote>("0-201-82470-1", 50));basket.push_back(    make_shared<Bulk_quote>("0-201-54848-8", 50, 10, .25));// calls the version defined by Quote; prints 562.5, i.e., 15 * $50 less the discountcout << basket.back()->net_price(15) << endl;

Because basket holds shared_ptrs, we must dereference the value returned by basket.back() ...

Get C++ Primer, Fifth Edition 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.