Chapter 5. Streaming Your Own Classes

In This Chapter

  • Streaming a class to a text file

  • Getting the most out of manipulators

  • Writing your own manipulators

The C++ stream classes can read and write all sorts of goodies, such as integers, characters, strings, floating-point numbers, and Boolean variables. But sooner or later, being able to stream one of your own classes (like the following) would be nice:

MyClass x;
cout << x << endl;

Now C++ has a good reason not to have done this already: The compiler and library can't know how to stream your class. What should cout write? The name of the class followed by the values of the public member variables? Or maybe just the private member variables? None of the above?

Therefore, you should make the class streamable. In this chapter, we show you how to do it. But recognizing that you have two separate reasons why you may want to make a class streamable is important:

  • To provide a format for writing the object to a text stream.

  • To save the information in an object so you can read it back in at a later date, thereby reconstructing the object. A class with this feature is called a persistent class.

We cover both topics in this chapter. We also show how you can create your own manipulators. Remember, a manipulator is this kind of code:

cout << endl;

That is, the endl is the manipulator. You can make your own manipulators that manipulate the stream in various ways, as we show you later in this chapter.

Streaming a Class for Text Formatting

When dealing with ...

Get C++ All-In-One For Dummies®, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.