Dumping Object Contents

This topic explains how to get a diagnostic dump of the contents of your objects.

When deriving a class from CObject, you have the option to override the Dump member function and write a textual representation of the object’s member variables 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.

You do not have to override Dump when you derive a class from CObject. However, if you use other diagnostic features for debugging, providing the capability for dumping an object and viewing its contents is very helpful and highly recommended.

Note   Before you can dump objects, you must enable diagnostic tracing so you can see the results of your dump in the debugger. For more information, see Diagnostics.

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 of your derived class.

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

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 you are debugging your program, the declaration of the Dump function is bracketed with an #ifdef _DEBUG / #endif block.

In the following example from an implementation file for the class CPerson, the Dump function’s first statement calls the Dump member function for its base class. It then writes a short description of each member variable along with the member’s value to the diagnostic stream.

#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 << "\n";
}
#endif

Note   Again, notice that the definition of the Dump function is bracketed by #ifdef _DEBUG / #endif directives. If you refer to afxDump in a program linked with the nondebug libraries, you will get unresolved externals errors at link time.

To send Dump output to afxDump

For more information, see The TRACE Macro.