home *** CD-ROM | disk | FTP | other *** search
- // Chap14_3.cpp
- // this version works properly
- #include <iostream.h>
- #include <string.h>
- class Person
- {
- public:
- Person(char *pN)
- {
- cout << "Constructing " << pN << "\n";
- pName = new char[strlen(pN) + 1];
- if (pName != 0)
- {
- strcpy(pName, pN);
- }
- }
- //copy constructor allocates a new heap block
- Person(Person &p)
- {
- cout << "Copying " << p.pName << " into its own block\n";
- pName = new char[strlen(p.pName) + 1];
- if (pName != 0)
- {
- strcpy(pName, p.pName);
- }
- }
- ~Person()
- {
- cout << "Destructing " << pName << "\n";
- //letÆs wipe out the name just for the heck of it
- pName[0] = '\0';
- delete pName;
- }
- protected:
- char *pName;
- };
-
- int main()
- {
- Person p1("Randy");
- Person p2 = p1; //invoke the copy constructor...
- return 0; //...equivalent to Person p2(p1);
- }
-