home *** CD-ROM | disk | FTP | other *** search
/ C++ for Dummies (3rd Edition) / C_FD.iso / CHAP14 / CHAP14_4.CPP < prev   
C/C++ Source or Header  |  1996-09-02  |  956b  |  44 lines

  1. // Chap14_3.cpp
  2. // this version works properly
  3. #include <iostream.h>
  4. #include <string.h>
  5. class Person
  6. {
  7.   public:
  8.    Person(char *pN)
  9.    {
  10.       cout << "Constructing " << pN << "\n";
  11.       pName = new char[strlen(pN) + 1];
  12.       if (pName != 0)
  13.       {
  14.           strcpy(pName, pN);
  15.       }
  16.    }
  17.    //copy constructor allocates a new heap block
  18.    Person(Person &p) 
  19.    {
  20.       cout << "Copying " << p.pName << " into its own block\n";
  21.       pName = new char[strlen(p.pName) + 1];
  22.       if (pName != 0)
  23.       {
  24.          strcpy(pName, p.pName);
  25.       }
  26.    }
  27.   ~Person()
  28.    {
  29.       cout << "Destructing " << pName << "\n";
  30.       //letÆs wipe out the name just for the heck of it
  31.       pName[0] = '\0';
  32.       delete pName;
  33.    }
  34.   protected:
  35.    char *pName;
  36. };
  37.  
  38. int main()
  39. {
  40.    Person p1("Randy");
  41.    Person p2 = p1;       //invoke the copy constructor...
  42.    return 0;             //...equivalent to Person p2(p1);
  43. }
  44.