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 predict on their own how you want 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 keep in mind that you have (at least) two separate reasons why you may want to make a class streamable:
- 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 ...
Get C++ All-in-One For Dummies, 3rd 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.