C++ Inheritance and Polymorphism
- 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
- Complete Program Output
- Make Your Destructors Virtual
- Additional Reading
Inheritance provides what is possibly the strongest argument in favor of object-oriented languages such as C++. An important aspect of effectively using inheritance is that the structure used should match your domain as closely as possible. The last few years have seen the emergence of software that mimics processes found in nature; for example, genetic algorithms for auto-learning. This is pretty powerful stuff and it demonstrates a type of code reuse in that if nature has perfected these processes over millions of years, why not tap into the wealth? In other words, it’s important to closely match your use of inheritance with the specifics of your application domain.
Similar arguments apply to polymorphism, but the slant I take in this article is the way effective use of inheritance and polymorphism allows for economical solutions; that is, less code. Again, just look at nature, in which where balance and economy abound. Less code means less testing, lower maintenance costs, and easier upgrades.
The application domain I look at in this article is document management. As usual, Listing 1 shows a sneak preview of the finished code, in which I do the following:
- I create a memo document object.
- I create an invoice document object.
- I create a contract document object.
- I manipulate these three documents as part of organizational workflows.
- I delete the three objects.
Listing 1 Creation, Use, and Deletion of the Three Document Types
MemoDocument* aMemoDoc = new MemoDocument(222, "Calling All Employees", MEMO); InvoiceDocument* anInvoiceDoc = new InvoiceDocument(133, "A Big Customer", INVOICE, 3500); ContractDocument* aContractDoc = new ContractDocument(285, "An Organization", CONTRACT, 1000); // Various workflows // Sending documents to recipients // Signing documents, archiving, etc. // Then finally... delete aMemoDoc; delete anInvoiceDoc; delete aContractDoc;
I mention workflows because this term is becoming increasingly important in IT. It reflects a trend toward using IT to facilitate business needs. In a way, we can probably expect that IT will be used in the same way as businesses use electricity, buildings, and so on. That is, IT will become a basic business commodity or utility.
The document types in Listing 1 are derived from a common base class.