August 2012
Intermediate to advanced
976 pages
30h 17m
English
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() ...
Read now
Unlock full access