October 2011
Beginner to intermediate
1200 pages
35h 33m
English
The new default constructor merits notice. It look likes this:
String::String(){ len = 0; str = new char[1]; str[0] = '\0'; // default string}
You might wonder why the code uses
str = new char[1];
and not this:
str = new char;
Both forms allocate the same amount of memory. The difference is that the first form is compatible with the class destructor and the second is not. Recall that the destructor contains this code:
delete [] str;
Using delete [] is compatible with pointers initialized by using new [] and with the null pointer. So another possibility would be to replace
str = new char[1];str[0] = '\0'; // default string
with this:
str = 0; // sets str to the null pointer
Read now
Unlock full access