Search code examples
c++assertassertioninvariants

Proper use of assert() in c++


My professor gave us a exercise where we have to decide when it's appropriate to use the assert(check_inv()) that keeps the objected in a state well-formed respecting the class invariant.

I'm not sure when it's necessary to check the class invariant, i know that before returning a object from his constructor is a good practice checking the class invariant, but in case of other functions i'm not completely sure.

this is the exam text:

class C
{ 

    public: 

        bool check_inv() const 
        { 
            // Implementation of class invariant code
        }

        C(int a, int b)
        { 
            // Implementation of class constructor.
        }
        void foo(C& y)
        {
            // Implementation of method foo. 
        }
        void bar(const C& y)
        { 
             // Implementation of method bar.
        }
        void ying(const C& y)
        { 
            // Implementation of method ying. 
        }
        void yang(const C& y) const
         { 
             // Implementation of method yang.
         }
        ~C()
         { 
             // Implementation of class destructor.
         }
        static void zen(int i, double d) 
        { 
            //Implementation of method zen.
        }
// ... Some other code ...
}; // class C

Where should i check the class invariant?

EDIT: this isn't supposed to be homework question at all, i just need to understand the functioning of assertions through an example.


Solution

  • Think about the life cycle of an object: it gets created by a constructor, it gets examined by const member functions, it gets modified by non-const member functions, and eventually it gets destroyed by its destructor. So as far as the class invariant goes, it must be satisfied at the end of the constructor and at the end of any non-const member functions. That's sufficient to ensure that the invariant is satisfied everywhere. Checking it on entry into a function doesn't make the class robust; it might detect overwrites from outside, but that's not part of the abstraction that the class presents. So: check the invariant at the end of each constructor and at the end of each non-const member function.