The Implementation

This message system makes use of the fact that the output from a C++ program is handled by the cout object. This is an object of type ostream, and is provided by the C++ system. It is important to note that the cout object is merely the formatting engine which assembles a string from the input parameters. The actual output is handled by yet another object of class streambuf. So if there is a statement like
	int i = 5;
	cout << "This is a message " << i << endl;
the cout object will take care of all the formatting and will end up with a string
This is a message 5
which is then handed off to the streambuf object to be sent to the standard output.

The cout object comes with a ready-made streambuf object which will talk to standard output. However, at runtime you can give cout another object of type streambuf to use instead, one which will treat the output the way you want. This streambuf object is not at all involved in formatting the output, all this is already taken care of by cout itself. The streambuf object is only responsible with delivering the message to its destination.

So this is the way our message handler works:

  1. We create an instance of our custom message handler class which inherits from streambuf and can as such replace cout's original streambuf.

  2. In its constructor, it establishes itself as cout's new streambuf object. It preserves a pointer to the original streambuf, so it can undo its action later by re-establishing cout's original streambuf.

  3. Each time the <<endl function is invoked on cout, cout will call a member function of its streambuf object (now our custom-made object) to request that the preformatted output string be disposed of. It is here that we get hold of the fully formatted string and can deal with it in whatever way we need.

  4. If we delete the custom streambuf object, it re-establishes the original streambuf which cout had when we created our streambuf object.

Alphabetic index Hierarchy of classes



This page was generated with the help of DOC++.