Looking Again at new and delete
Note that the program generated from Listings 12.4, 12.5, and 12.7 uses new and delete on two levels. First, it uses new to allocate storage space for the name strings for each object that is created. This happens in the constructor functions, so the destructor function uses delete to free that memory. Because each string is an array of characters, the destructor uses delete with brackets. Thus, memory used to store the string contents is freed automatically when an object is destroyed. Second, the code in Listing 12.7 uses new to allocate an entire object:
String * favorite = new String(sayings[choice]);
This allocates space not for the string to be stored but for the object—that is, for the str pointer that holds ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access