Overriding the AssertValid Function

The AssertValid member function is provided in CObject to allow run-time checks of an object's internal state. Although it is not required that you override AssertValid when you derive your class from CObject, you can make using your class safer and more reliable by overriding AssertValid.

Typically, AssertValid performs assertions on all the object's member variables to see if they contain valid values. For example, AssertValid can check that all pointer member variables are not NULL. AssertValid asserts and halts the program if it finds that the object is invalid. Because it uses the ASSERT macro, AssertValid will have no effect when used in the Release version of the library.

The declaration of the AssertValid function in the class declaration looks like this:

class CPerson : public CObject

{

protected:

CString m_Name;

float m_Salary;

public:

virtual void AssertValid() const;

// etc. ...

};

In your overriding AssertValid, first call AssertValid for the base class. Then, assert the validity of the members that are unique to your derived class, as shown by the following example:

void CPerson::AssertValid()

{

// call inherited AssertValid first

CObject::AssertValid()

// check CPerson members...

ASSERT( m_Name != NULL )

ASSERT( m_Salary != 0 )

}

Users of an AssertValid function of a given class should not rely too heavily on the accuracy of this function. A triggered assertion indicates that the object is definitely bad and execution will be halted. A lack of assertion indicates that no problem was found, but the object isn't guaranteed to be good.