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.
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).
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();
};
Form* pForm[10]
//create Expense/Loan/Purchase Forms…
for (short i=0 ; i < 9 ; i++)
pForm->print();
Here ten objects are created 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.
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.
Example of polymorphic behavior
The following sample can be found in the samples directory as file ICC$RES2. It is presented here without the terminal IO requests. See C++ sample programs.
#include "icceh.hpp"
#include "iccmain.hpp"
char* dataItems[] =
{
"Hello World - item 1",
"Hello World - item 2",
"Hello World - item 3"
};
void IccUserControl::run()
{
IccBuf buffer( 50 );
IccResource* pObj[2];
pObj[0] = new IccDataQueue("ICCQ");
pObj[1] = new IccTempStore("ICCTEMPS");
for ( short index=0; index <= 1 ; index++ )
{
pObj[index]->clear();
}
for ( index=0; index <= 1 ; index++ )
{
for (short j=1 ; j <= 3 ; j++)
{
buffer = dataItems[j-1];
pObj[index]->put( buffer );
}
}
for ( index=0; index <= 1 ; index++ )
{
buffer = pObj[index]->get();
while (pObj[index]->condition() == IccCondition::NORMAL)
{
buffer = pObj[index]->get();
}
delete pObj[index];
}
return;
}
The data items are read back in from each of our resource objects using the get method. We delete the resource objects and return control to CICS®.