Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend


In one sentence, polymorphism is all about virtual functions, which allows for derived objects to change the structure and makeup of functions defined in base classes. Let’s see how this applies to the generic base class AnyOldDocument. Let’s assume that our document management system supports the archiving of its various document classes. The base class already has placeholders for such functions as shown by the three base class member functions in Listing 7.

Listing 7 Using the Base Class Member Functions

  virtual void StoreDocument() {};
  virtual void GetDocument() {};
  virtual void DeleteDocument() {};

An important aspect of polymorphism is the capability to bind code to these functions based on the type of the caller. Let’s make this more concrete by assuming that invoices are stored in one content management system, and contracts are stored in another. The derived classes InvoiceDocument and ContractDocument must supply specific code to these member functions. Listing 8 shows the addition of the member function StoreDocument() to the ContractDocument class.

Listing 8 Addition to the ContractDocument Class

class ContractDocument : AnyOldDocument {
  explicit ContractDocument(int Id, char* name, int docType, int number);
  virtual ~ContractDocument();
  const int getPenaltyClauseValue();
  void setPenaltyClauseValue(int number);
  virtual void StoreDocument(); // New addition

Please note that it’s not necessary to use the keyword virtual in the declaration of StoreDocument(). However, it is good practice to indicate that this is a virtual function; for example, if you wanted to later review your use of virtual functions. The latter might arise if you were looking at performance.

So, how do we use this new function? Listing 9 shows the member function definition in ContractDocument.

Listing 9 Calling the StoreDocument() function

void ContractDocument::StoreDocument()
  printf("Now storing contract to archive\n");

Listing 9 just shows a simple printf() statement. In a real system, we would typically call into some external content management system to archive the contract. Similar considerations apply to archiving invoices.

  • + Share This
  • 🔖 Save To Your Account