EECS 211
How to read Chapters 9 and 10

Chapters 9 and 10 go into more detail on issues in C++ when defining classes. There's no particular reason for splitting these into separate chapters.

Some important points to pay attention to:

Initialization Lists

Use initialization lists to give default values to data members. Deitel calls these "member initializations" and introduces them in Chapter 10, but they're worth getting used to right away.

For example, in their Time constructor (Figure 9.2), they have:

   hour = minute = second = 0;

An initialization list version would look like this:

Time::Time() : hour(0), minute(0), second(0)

Similarly, the constructor for Date (Figure 9.18) would look like this:

Date::Date(int m, int d, int y) : month(m), day(d), year(y)

Not only are initialization lists somewhat shorter, but, with more complex data types, they are more efficient. In Chapter 10, a number of Deitel's programming notes talk about when you have to use initialization lists.


The general rule of thumb is that if your constructor calls new to allocate memory (Chapter 10, Section 6), then your destructor should call delete to deallocate it. Otherwise, your program will "leak" memory. The metaphor of leaking memory is standard, but odd. A program with memory leaks will run out of memory if run long enough, but not because the memory leaked away somehow. Rather, the program has repeatedly asked for, been given, and then lost track of all available memory. It's more like someone running out of money because he keeps taking some from the bank, then misplacing it.