Sams Teach Yourself C++ in 21 Days

(singke) #1
What’s Next 769

21


String Tested OK String Tested OK String Tested OK String Tested OK
String Tested OK String Tested OK String Tested OK String Tested OK
String Tested OK StringTested OK String Tested OK String Tested OK
String Tested OK String Tested OK Animal Tested OK String Tested OK
Animal Tested OK
Sparky is Animal Tested OK 5 years old.Animal Tested OK Animal Tested OK
Animal
Tested OK
Sparky is Animal Tested OK 8 years old.String Tested OK
On lines 9–15, the ASSERT()macro is defined. If DEBUGis defined, this writes out
an error message when the ASSERT()macro evaluates false.
On line 39, the Stringclass member function Invariants()is declared; it is defined on
lines 143–150. The constructor is declared on lines 49–55; on line 54, 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()before taking any action and then again before returning. This both
affirms and validates a fundamental principle of C++: Member functions other than con-
structors and destructors should work on valid objects and should leave them in a valid
state.
On line 176, class Animaldeclares its own Invariants()method, implemented on lines
189–195. Note on lines 155, 158, 161, and 163 that inline functions can call the
Invariants()method.

Printing Interim Values ..................................................................................


In addition to asserting that something is true using the ASSERT()macro, you might want
to print the current value 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.

LISTING21.5 Printing Values in DEBUGMode


0: // Listing 21.5 - Printing values in DEBUG mode
1: #include <iostream>
2: using namespace std;
3: #define DEBUG
4:
5: #ifndef DEBUG
6: #define PRINT(x)

OUTPUT


ANALYSIS
Free download pdf