Advanced Inheritance 587
16
41: // ConstructorCount++;
42: }
43:
44: // private (helper) constructor, used only by
45: // class methods for creating a new string of
46: // required size. Null filled.
47: String::String(int len)
48: {
49: itsString = new char[len+1];
50: for (int i = 0; i<=len; i++)
51: itsString[i] = ‘\0’;
52: itsLen=len;
53: // cout << “\tString(int) constructor” << endl;
54: // ConstructorCount++;
55: }
56:
57: // Converts a character array to a String
58: String::String(const char * const cString)
59: {
60: itsLen = strlen(cString);
61: itsString = new char[itsLen+1];
62: for (int i = 0; i<itsLen; i++)
63: itsString[i] = cString[i];
64: itsString[itsLen]=’\0’;
65: // cout << “\tString(char*) constructor” << endl;
66: // ConstructorCount++;
67: }
68:
69: // copy constructor
70: String::String (const String & rhs)
71: {
72: itsLen=rhs.GetLen();
73: itsString = new char[itsLen+1];
74: for (int i = 0; i<itsLen;i++)
75: itsString[i] = rhs[i];
76: itsString[itsLen] = ‘\0’;
77: // cout << “\tString(String&) constructor” << endl;
78: // ConstructorCount++;
79: }
80:
81: // destructor, frees allocated memory
82: String::~String ()
83: {
84: delete [] itsString;
85: itsLen = 0;
86: // cout << “\tString destructor” << endl;
87: }
88:
89: // operator equals, frees existing memory
90: // then copies string and size
91: String& String::operator=(const String & rhs)
92: {
LISTING16.9 continued