


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



#include
/* Working program for hw#4 question 2.
This program compiles and runs using the egcs-1.1.2 compiler under linux. This version of the compiler doesn’t require namespace business. */
class ItemBase
Used in polyList construction as base class for arbitrary objects. An abstract class. */ class ItemBase { public: virtual void print() = 0; virtual ~ItemBase() {} };
class Item
Templatized class used to hold arbitrary data objects. Simply holds a T object. The only derived class of ItemBase. Implements the print() method, and also provides an accessor that is not available in the ItemBase class. */ template
class polyList
Heterogeneous list. Implemented as STL list of ItemBase pointers. Use of pointers necessary to avoid loss of data when each Item
class polyList { public: template
polyList::insert
Templatized function to allow insertions of arbitrary types into lst. Creates an Item
/ template
polyList::~polyList
Destructor for polyList class. Iterates through list to delete objects. Necessary because list holds pointers. Requires virtual destructor in ItemBase. / polyList::~polyList() { list<ItemBase>::iterator l_i = lst.begin(); ItemBase* d; while (l_i != lst.end()) { d = *l_i++; delete d; } }
void main() { polyList l; l.insert(1); l.insert(string("two")); //this is a difference from example code l.print(); string s; try { if (!l.isEmpty()) l.extract(s); } catch (polyList::WrongType) { cout << "type error" << endl; } l.print(); int i; try { if (!l.isEmpty()) l.extract(i); cout << "i: " << i << endl; } catch (polyList::WrongType) { cout << "type error" << endl; } l.print();