home *** CD-ROM | disk | FTP | other *** search
/ C++ for Dummies (3rd Edition) / C_FD.iso / CHAP15 / CHAP15_1.CPP next >
C/C++ Source or Header  |  1996-09-15  |  952b  |  49 lines

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