/////////////////////////////////////////////////////////////// // basic2.cpp - declare generic class, create & use objects // // ver 2 // // Jim Fawcett, CSE687, S99 // /////////////////////////////////////////////////////////////// #include using namespace std; template class basic { public: basic(const char *inMsg, const T t); ~basic(); void showMsg() const; // const member functions don't // change object's state private: char* pMsg; T param; // make these private and unimplemented so copying and // assignment are prohibited, even by members of this class basic(const basic &b); basic& operator=(const basic &b); }; //----< constructor >-------------------------------------------- template basic::basic(const char *inMsg, const T t) : param(t) { std::cout << "\n constructing object\n"; pMsg = new char[strlen(inMsg)+1]; if(!pMsg) throw "\n memory allocation failure\n\n"; strcpy(pMsg,inMsg); } //----< destructor >------------------------------------------- template basic::~basic() { delete [] pMsg; std::cout << "\n destroying object\n"; } //---< display - show message >-------------------------------- template void basic::showMsg() const { cout << " " << pMsg << " " << param << "\n"; } //----< test >------------------------------------------------- // Note: This global function must be template and must pass by // reference since copying is prohibited. template void caller(const basic &b) { cout << "\n caller using reference to basic object\n"; b.showMsg(); } void main() { std::cout << "\n Demonstrate Basic Template Class Operation " << "\n ============================================\n"; basic myObj1("first object has param ", -7); myObj1.showMsg(); basic myObj2("second object has param ", 3.33e-33); myObj2.showMsg(); basic myObj3("third object has param ", 'z'); myObj3.showMsg(); caller(myObj1); }