Polymorphic Behavior

Polymorphism ( poly = many, morphe = form) is the ability to treat many different forms of an object as if they were the same.

Polymorphism is achieved in C++ by using inheritance and virtual functions. Consider the scenario where we have three forms (ExpenseForm, LoanForm, PurchaseForm) that are specializations of a general Form:
Hierarchy of Form classes with parent class Form and children classes ExpenseForm, LoanForm, and PurchaseForm

Each form needs printing at some time. In procedural programming, we would either code a print function to handle the three different forms or we would write three different functions (printExpenseForm, printLoanForm, printPurchaseForm).

In C++, this can be achieved far more elegantly as follows:
 class Form {
public:
virtual void print();
};
class ExpenseForm : public Form {
public:
virtual void print();
};
class LoanForm : public Form {
public:
virtual void print();
};
class PurchaseForm : public Form {
public:
virtual void print();
};
Each of these overridden functions is implemented so that each form prints correctly. Now an application using form objects can do this:

Form* pForm[10]
//create Expense/Loan/Purchase Forms…
for (short i=0 ; i < 9 ; i++)
pForm->print();

Here we create ten objects that might be any combination of Expense, Loan, and Purchase Forms. However, because we are dealing with pointers to the base class, Form , we do not need to know which sort of form object we have; the correct print method is called automatically.

Limited polymorphic behavior is available in the Foundation Classes. Three virtual functions are defined in the base class IccResource :

virtual void clear();
virtual const IccBuf& get();
virtual void put(const IccBuf&

buffer

);

These methods have been implemented in the subclasses of IccResource wherever possible:

Class clear get put
IccConsole × ×
IccDataQueue
IccJournal × ×
IccSession ×
IccTempStore
IccTerminal

These virtual methods are not supported by any subclasses of IccResource except those in the table.

Note: The default implementations of clear , get , and put in the base class IccResource throw an exception to prevent the user from calling an unsupported method.