MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev

Debugging hints

When you're writing your own classes, you can use the features of C++ to your advantage and build in debugging tools. In particular, each class should have a function called dump( ) (or some similar name) that will display the contents of an object. This way you can dump( ) your objects at various points in your program to trace their progress. If you build the dump( ) function in from the start, you won't have as much mental resistance to running a trace.

This class has a built-in dump( ) function:

//: C03:Debug1.cpp
// A class with a dump() function
#include <iostream>
using namespace std;

class Debuggable {
  int counter; // Some sort of internal counter
  float a, b;  // Data the user is aware of
public:
  Debuggable(float x = 0.0, float y = 0.0) {
    a = x; b = y; counter = 2;
  }
  void set_a(float x) { a = x; counter++; }
  float read_a() { return a; counter++; }
  void set_b(float y) { b = y; counter++; }
  float read_b() { counter++; return b; }
  void dump(char * msg = "") {
    cout << msg << ":" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "counter = " << counter << endl;
  }
};
int main() {
  Debuggable U, V(3.14), W(1.1,2.2);
  U.set_a(99);
  U.dump("After 1 set_a");
  U.read_b();
  U.dump("After 1 read_b");
  // Other operations ...
  V.dump("V");
  W.dump();  // string argument is optional
} ///:~ 

Because the argument msg is given a default value of an empty string, providing a message when you call dump( ) is optional. In this program, the variable counter is normally completely hidden from the user's view, and no functions are provided to access it. counter is a variable to keep track of some sort of internal information. When debugging, this information may be essential. It is best to provide as much information as possible, as well as optional messages, in the dump( ) function.

––––––––––––––––––––––––––––––––––––––––––––––––––––

Contents | Prev


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru