/////////////////////////////////////////////////////////////// // basic3.cpp - demonstrate aggregation // // declare contained class and containing class, // // create container, and use objects // // ver 3 // // Jim Fawcett, CSE687, S98 // /////////////////////////////////////////////////////////////// #include using namespace std; //////////////////////////////////////////////////////////////// // contained class declaration // //////////////////////////////////////////////////////////////// class basic { public: basic(const char *inMsg); ~basic(); void showMsg(); private: char* pMsg; // 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 >------------------------------------------ basic::basic(const char *inMsg) { std::cout << "\n constructing contained object\n"; pMsg = new char[strlen(inMsg)+1]; if(!pMsg) throw "\n memory allocation failure\n\n"; strcpy(pMsg,inMsg); } //----< destructor >------------------------------------------- basic::~basic() { delete [] pMsg; } //----< display >---------------------------------------------- void basic::showMsg() { cout << " " << pMsg << "\n"; } //////////////////////////////////////////////////////////////// // container class declaration // //////////////////////////////////////////////////////////////// class containerOFbasic { public: containerOFbasic(const char *inMsg, const char *basicMsg); void showMsg(); private: char *pMsg; basic inHere; // contained object - can't be void constructed // because no void ctor is defined but one ctor is // defined (which prevents simple component-wise // construction) }; //----< constructor with initialization >---------------------- containerOFbasic:: containerOFbasic(const char *inMsg, const char *basicMsg) : inHere(basicMsg) { cout << "\n constructing container object\n"; pMsg = new char[strlen(inMsg)+1]; if(!pMsg) throw "\n memory allocation failure\n\n"; strcpy(pMsg,inMsg); } //----< display message >-------------------------------------- void containerOFbasic::showMsg() { cout << " " << pMsg << endl; inHere.showMsg(); } //----< test >------------------------------------------------- void main() { cout << "\n Demonstrate Basic Aggregation " << "\n ===============================\n"; char *outerMsg1 = "I'm a container -- this is all I do"; char *innerMsg1 = "I'm contained"; containerOFbasic Obj1(outerMsg1, innerMsg1); Obj1.showMsg(); char *outerMsg2 = "I'm another container"; char *innerMsg2 = "Help -- I'm trapped in here"; containerOFbasic Obj2(outerMsg2, innerMsg2); Obj2.showMsg(); }