< previous page page_364 next page >

Page 364
LISTING 21.4 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
179:  #ifdef SHOW_INVARIANTS
180:     cout <<  Animal OK ;
181:  #endif
182:     return (itsAge > 0 && itsName.GetLen());
183:  }
184:
185:  int main()
186:  {
187:     Animal sparky(5,Sparky);
188:     cout << \n << sparky.GetName().GetString() <<  is ;
189:     cout << sparky.GetAge() <<  years old.;
190:     sparky.SetAge(8);
191:     cout << \n << sparky.GetName().GetString() <<  is ;
192:     cout << sparky.GetAge() <<  years old.;
193:     return 0;
194:  }

Output:
String OK String OK String OK String OK String OK String OK
String OK String OK Animal OK String OK Animal OK
Sparky is Animal OK 5 years old. Animal OK Animal OK Animal OK
Sparky is Animal OK 8 years old. String OK
On lines 616, the assert() macro is defined. If DEBUG is defined, this macro will write out an error message when the assert() macro evaluates false.
On line 33, the String class member function Invariants() is declared; it is defined on lines 135141. The constructor is declared on lines 2224, and on line 36, after the object is fully constructed, Invariants() is called to confirm proper construction.
This pattern is repeated for the other constructors, and the destructor calls Invariants() only before it sets out to destroy the object. The remaining class functions call Invariants() both before taking any action and then again before returning. This both affirms and validates a fundamental principal of C++: Member functions other than constructors and destructors should work on valid objects and should leave them in a valid state.
On line 164, class Animal declares its own Invariants() method, implemented on lines 177183. Note on lines 147, 150, 153, 155, 160, and 162 that inline functions can call the Invariants() method.
Printing Interim Values.
In addition to asserting that something is true using the assert() macro, you may want to print the current values of pointers, variables, and strings. This can be very helpful in checking your assumptions about the progress of your program and in locating off-by-one bugs in loops. Listing 21.5 illustrates this idea.

 
< previous page page_364 next page >

If you like this book, buy it!