/////////////////////////////////////////////////////////////// // basic4.cpp - declare base class and derived class // // create and use objects // // ver 2 // // Jim Fawcett, CSE687, S99 // /////////////////////////////////////////////////////////////// #include /////////////////////////////////////////////////////////////// // base class declaration // /////////////////////////////////////////////////////////////// class basic { public: basic(const char *inMsg); virtual ~basic(); virtual void showMsg(); protected: char* pMsg; basic(const basic &b); basic& operator=(const basic &b); }; //----< constructor >------------------------------------------ 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); } //----< destructor >------------------------------------------- basic::~basic() { delete [] pMsg; std::cout << "\n destroying object\n"; } //----< display message >-------------------------------------- void basic::showMsg() { std::cout << " " << pMsg << "\n"; } // /////////////////////////////////////////////////////////////// // derived class declaration // /////////////////////////////////////////////////////////////// class almostASbasic : public basic { public: almostASbasic(char *inMsg); virtual ~almostASbasic(); virtual void showMsg(); private: static int numObjs; // number created so far int count; // my number }; int almostASbasic::numObjs = 0; //----< constructor with initialization >---------------------- almostASbasic::almostASbasic(char *inMsg) : basic(inMsg) { count = ++numObjs; } //----< destructor >------------------------------------------- almostASbasic::~almostASbasic() { /* nothing to do */ } //----< display >---------------------------------------------- void almostASbasic::showMsg() { std::cout << " " << pMsg << count << "\n"; } //----< test >------------------------------------------------- void caller(almostASbasic aab) { std::cout << "\n caller using basic object\n"; aab.showMsg(); } void main() { std::cout << "\n Demonstrating Basic Inheritance " << "\n =================================\n"; basic myObj1("this is a message from first base object"); myObj1.showMsg(); basic myObj2("this is a message from second base object"); myObj2.showMsg(); almostASbasic yourObj1("this is a message from derived object #"); yourObj1.showMsg(); almostASbasic yourObj2("this is a message from derived object #"); yourObj2.showMsg(); // caller(myObj1); // compile error because copying basic // objects is prohibited // caller(yourObj1); // linker error: copying almostASbasic objects // is not prohibited, but there is no copy // ctor defined for internal basic obj }