Now we can reimplement Bulk_quote
to inherit from Disc_quote
rather than inheriting directly from Quote
:
// the discount kicks in when a specified number of copies of the same book are sold
// the discount is expressed as a fraction to use to reduce the normal price
class Bulk_quote : public Disc_quote {
public:
Bulk_quote() = default;
Bulk_quote(const std::string& book, double price,
std::size_t qty, double disc):
Disc_quote(book, price, qty, disc) { }
// overrides the base version to implement the bulk purchase discount policy
double net_price(std::size_t) const override;
};
This version of Bulk_quote
has a direct base class, Disc_quote
, and an indirect base class, Quote
. Each Bulk_quote
object has three subobjects: an (empty) Bulk_quote
part, a Disc_quote
subobject, and a Quote
subobject.
As we’ve seen, each class controls the initialization of objects of its type. Therefore, even though Bulk_quote
has no data members of its own, it provides the same four-argument constructor as in our original class. Our new constructor passes its arguments to the Disc_quote
constructor. That constructor in turn runs the Quote
constructor. The Quote
constructor initializes the bookNo
and price
members of bulk
. When the Quote
constructor ends, the Disc_quote
constructor runs and initializes the quantity
and discount
members. At this point, the Bulk_quote
constructor resumes. That constructor has no further initializations or any other work to do.
Adding Disc_quote
to the Quote
hierarchy is an example of refactoring. Refactoring involves redesigning a class hierarchy to move operations and/or data from one class to another. Refactoring is common in object-oriented applications.
It is noteworthy that even though we changed the inheritance hierarchy, code that uses Bulk_quote
or Quote
would not need to change. However, when classes are refactored (or changed in any other way) we must recompile any code that uses those classes.
Exercise 15.15: Define your own versions of Disc_quote
and Bulk_quote
.
Exercise 15.16: Rewrite the class representing a limited discount strategy, which you wrote for the exercises in § 15.2.2 (p. 601), to inherit from Disc_quote
.
Exercise 15.17: Try to define an object of type Disc_quote
and see what errors you get from the compiler.