FAQ 10.07 What is a class invariant?

Stuff that's true whenever anyone else is looking.

The class invariant is the collection of boolean expressions that are always true for objects of the class. It is normal for a member or friend function (see FAQ 19.05) to temporarily violate the invariant, but the member or friend function must restore the invariant before returning to the user.

Here is the invariant for a Date class, encoded in the protected: testInvariant() member function.

 #include <cassert> class Date { public:                                                      <-- 1 protected:   void testInvariant() const throw();   int day_;   int month_;   int year_; }; inline void Date::testInvariant() const throw() {   assert(day_ >= 1 && day_ <= 31);   assert(month_ >= 1 && month_ <= 12); } 

(1) The public: interface for Date goes here

The statement assert(month_ >= 1 && month_ <= 12); evaluates the conditional as a boolean. If month_ is out of range, the assertion fails and the assert() statement causes an error message to be printed and the program to be killed. During development, the debugger often opens at this point so that the programmer can determine exactly what went wrong and why. Compiling with the symbol NDEBUG defined (for example, via the -DNDEBUG option on many command-line driven compilers) causes the assert(...) code to vanish completely.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net