home *** CD-ROM | disk | FTP | other *** search
/ C++ for Dummies (3rd Edition) / C_FD.iso / CHAP22 / CHAP22_1.CPP
C/C++ Source or Header  |  1996-09-02  |  1KB  |  65 lines

  1. // Chap22_1.cpp
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. class Name
  6. {
  7.   public:
  8.    Name()
  9.    {
  10.       pName = (char*)0;
  11.    }
  12.    Name(char *pN)
  13.    {
  14.       copyName(pN);
  15.    }
  16.    Name(Name& s)
  17.    {
  18.       copyName(s.pName);
  19.    }
  20.   ~Name()
  21.    {
  22.       deleteName();
  23.    }
  24.    //assignment operator
  25.    Name& operator=(Name& s)
  26.    {
  27.       //delete existing stuff...
  28.       deleteName();
  29.       //...before replacing with new stuff
  30.       copyName(s.pName);
  31.       //return reference to existing object
  32.       return *this;
  33.    }
  34.   protected:
  35.    void copyName(char *pN);
  36.    void deleteName();
  37.    char *pName;
  38. };
  39. //copyName() - allocate heap memory to store name
  40. void Name::copyName(char *pN)
  41. {
  42.    pName = (char*)malloc(strlen(pN) + 1);
  43.    if (pName)
  44.    {
  45.       strcpy(pName, pN);
  46.    }
  47. }
  48. //deleteName() - return heap memory
  49. void Name::deleteName()
  50. {
  51.    if (pName)
  52.    {
  53.       delete pName;
  54.       pName = 0;
  55.    }
  56. }
  57.  
  58. int main()
  59. {
  60.    Name s("Claudette");
  61.    Name t("temporary");
  62.    t = s;           //this invokes the assignment operator
  63.    return 0;
  64. }
  65.