/////////////////////////////////////////////////////////////// // basic1.cpp - declare class, create and use objects // // ver 2 // // Jim Fawcett, CSE687, S99 // /////////////////////////////////////////////////////////////// #include // cout #include // C style strings class basic { public: basic(const char *inMsg); basic(const basic& b); ~basic(); basic& operator=(const basic& b); void showMsg(); private: char* pMsg; // pointers need special care // when copying or assigning }; //----< constructor - stores message >------------------------- basic::basic(const char *inMsg) { std::cout << "\n constructing object\n"; pMsg = new char[strlen(inMsg)+1]; if(!pMsg) throw "\n memory allocation failure\n\n"; strcpy(pMsg,inMsg); } //----< copy constructor - safely copyies pointer pMsg >------- basic::basic(const basic& b) { std::cout << "\n copying object\n"; pMsg = new char[strlen(b.pMsg)+1]; if(!pMsg) throw "\n memory allocation failure\n\n"; strcpy(pMsg,b.pMsg); } //----< destructor - deallocates message storage >------------- basic::~basic() { delete [] pMsg; std::cout << "\n destroying object\n"; } // //----< assignment operator - safely assigns message >--------- basic& basic::operator=(const basic& b) { if(this == &b) return *this; delete [] pMsg; pMsg = new char[strlen(b.pMsg)+1]; if(!pMsg) throw "\n memory allocation failure\n\n"; strcpy(pMsg,b.pMsg); return *this; } //----< display - show message >------------------------------- void basic::showMsg() { std::cout << " " << pMsg << "\n"; } //----< test >------------------------------------------------- void caller(basic b) { // note pass-by-value std::cout << "\n caller using copy of basic object\n"; b.showMsg(); } void main() { std::cout << "\n Demonstrate Basic Class Operation " << "\n ===================================\n"; basic Obj1("this is a message from first object"); Obj1.showMsg(); basic Obj2("this is a message from second object"); Obj2.showMsg(); caller(Obj1); caller(Obj2); std::cout << "\n assigning Obj1 to Obj2:\n\n"; Obj2 = Obj1; Obj2.showMsg(); }