Sams Teach Yourself C++ in 21 Days

(singke) #1
When you pass the assert()statement,xreally is equal to 5 (you just set it!). Your pro-
gram runs just fine. You’re ready to ship it, so you turn off debugging. Now, the
assert()disappears, and you are no longer setting xto 5. Because xwas set to 0 just
before this, it remains at 0 and your program breaks.
In frustration, you turn debugging back on, but hey! Presto! The bug is gone. Again, this
is rather funny to watch, but not to live through, so be very careful about side effects in
debugging code. If you see a bug that only appears when debugging is turned off, take a
look at your debugging code with an eye out for nasty side effects.

Class Invariants ..............................................................................................


Most classes have some conditions that should always be true whenever you are finished
with a class member function. These class invariants are the sine qua non of your class.
For example, it might be true that your CIRCLEobject should never have a radius of zero
or that your ANIMALshould always have an age greater than zero and less than 100.
It can be very helpful to declare an Invariants()method that returns trueonly if each
of these conditions is still true. You can then ASSERT(Invariants())at the start and at
the completion of every class method. The exception would be that your Invariants()
would not expect to return truebefore your constructor runs or after your destructor
ends. Listing 21.4 demonstrates the use of the Invariants()method in a trivial class.

LISTING21.4 Using Invariants()
0: #define DEBUG
1: #define SHOW_INVARIANTS
2: #include <iostream>
3: #include <string.h>
4: using namespace std;
5:
6: #ifndef DEBUG
7: #define ASSERT(x)
8: #else
9: #define ASSERT(x) \
10: if (! (x)) \
11: { \
12: cout << “ERROR!! Assert “ << #x << “ failed” << endl; \
13: cout << “ on line “ << __LINE__ << endl; \
14: cout << “ in file “ << __FILE__ << endl; \
15: }
16: #endif
17:
18:
19: const int FALSE = 0;
20: const int TRUE = 1;

764 Day 21

Free download pdf