- The Takeaway
- Document Management
- The Base Class: AnyOldDocument
- Economy in Coding
- The First Document Type: A Memo
- The Second Document Typean Invoice
- The Third and Last Document Typea Contract
- Leveraging Base Class Generality
- Polymorphism
- Complete Program Output
- Make Your Destructors Virtual
- Conclusion
- Additional Reading
The Second Document Type—an Invoice
Just in case readers aren’t too sure what an invoice is, here’s a potted description! An invoice is usually submitted to a person or company when payment for some product or service is due. For example, if you get a contractor to update the central heating in your home, you’re likely to be presented with an invoice then when the job is finished. When the invoice is paid, the contractor’s accountant might also require a copy when completing the accounts for the year. So, there’s a workflow that centers around invoices; that is, they’re important documents. Listing 5 illustrates an invoice document class derived from AnyOldDocument. The main difference between the InvoiceDocument and the MemoDocument class is the addition of an integer parameter for price and two associated member functions.
Listing 5 InvoiceDocument—a Derived Class of AnyOldDocument
class InvoiceDocument : AnyOldDocument { public: explicit InvoiceDocument(int Id, char* name, int docType, int price); virtual ~InvoiceDocument(); int getPriceValue(); void setPriceValue(int number); }; InvoiceDocument::InvoiceDocument(int Id, char* name, int docType, int price) : AnyOldDocument(Id, name, docType, price) { printf ("Creating an invoice document for: %s\n", name); } InvoiceDocument::~InvoiceDocument() { } InvoiceDocument::getPriceValue() { return GetAssociatedNumber(); } void InvoiceDocument::setPriceValue(int number) { // Call into the base class member function SetAssociatedNumber(number); }
In the first line of Listing 5, we see that the new class InvoiceDocument is derived from the base class AnyOldDocument. Unlike the two-parameter constructor in the MemoDocument class (in Listing 3), the InvoiceDocument class has a three-parameter constructor. These three parameters map neatly into the private data members of the AnyOldDocument base class. The constructor for InvoiceDocument invokes the (three-parameter) base class constructor and passes in the three parameters.
The new price data item included in the constructor for InvoiceDocument serves to represent the price associated with the invoice. Remember the base class parameter called associatedNumber? Well, the latter is used to store the price parameter passed into the InvoiceDocument constructor. You might see a pattern emerging here. The base class is designed to be as abstract and general as possible. Then, derived classes are more specific—an invoice has a (specific) price entity that is mapped into the (generic) base class data member called associatedNumber. The latter is also used in the next document type described in the next section.