The Revised Default Constructor

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

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.