Dumping Object Contents

When deriving a class from CObject, you can optionally override the Dump member function to write a textual representation of the member variables of the object to a dump context, which is similar to an I/O stream. Like an I/O stream, you can use the insertion (<<) operator to send data to a CDumpContext.

Overriding Dump is not required when deriving a class from CObject, but it is very helpful and highly recommended when using the other diagnostic features for debugging to be able to dump an object and view its contents.

·To override the Dump member function:

1.Call the base class version of Dump to dump the contents of a base class object.

2.Write a textual description and value for each member variable for your derived class.

The declaration of the Dump function in the class declaration looks like the following example:

class CPerson : public CObject

{

public:

#ifdef _DEBUG

virtual void Dump( CDumpContext& dc ) const;

#endif

CString m_firstName;

CString m_lastName;

// etc. ...

};

Note:

Since object dumping only makes sense when debugging your programming, the declaration of the Dump function is bracketed with an #ifdef _DEBUG / #endif block.

The Dump function's first statement should call the Dump function for its base class. It should then write a short description of each member variable along with the member's value to the diagnostic stream, as shown by the following example from an implementation file for the class CPerson.

#ifdef _DEBUG

void CPerson::Dump( CDumpContext& dc ) const

{

// call base class function first

CObject::Dump( dc );

// now do the stuff for our specific class

dc << "last name: " << m_lastName << "\n"

<< "first name: " << m_firstName ;

}

#endif

Note:

Again, notice that the definition of the Dump function is bracketed by #ifdef _DEBUG / #endif directives.

·To send Dump output to afxDump:

You must supply a CDumpContext argument to specify where the dump output will go when you call the Dump function for an object. The Microsoft Foundation Class Library supplies a predefined CDumpContext object named afxDump that you will normally use for routine object dumping. The following example shows how to use afxDump:

CPerson myPerson = new CPerson;

// set some fields of the CPerson object...

//..

// now dump the contents

#ifdef _DEBUG

myPerson->Dump( afxDump );

#endif

In Windows, afxDump output is sent to the debugger, if present. In DOS, afxDump output is sent to stderr.

Note:

afxDump is defined only in the Debug version of the Microsoft Foundation Class Library.