iostreams Hierarchy


To provide seamless integration with existing code you need to create new classes that fit in with the existing iostreams hierarchy. To illustrate some of the relationships, Figure 1 contains a diagram of the ifstream path of the iostreams class hierarchy.

At the bottom of the hierarchy is the ifstream, ofstream, and fstream classes. You would normally use these classes when dealing with files as streams. These classes provide no new functions or data members, and each is completely dependent on its base classes for its abilities. They are derived multiply from fstreambase and one of the istream, ostream, or iostream classes.

The istream class gives ifstream all of its formatted input functionality. The >> operator is defined for all basic types, and get, getline, and read are also defined for reading. In addition, the control functions gcount, ignore, peek, putback, seekg, and tellg are defined. You should use the istream class whenever you create input functions for your user-defined types. The ostream class is similar but for output streams. The ostream class defines the functions flush, put, seekp, tellp, and write along with the < < operator. The iostream class is a "shell" class that simply inherits istream and ostream. All of these classes are virtually derived from the ios class. I will explain more on this later.

fstreambase gives fstream the ability to open and close a file. fstreambase defines the functions attach, close, open, rdbuf, and setbuf. It also contains a single data member, a filebuf type. This filebuf type gives fstream the ability to read and write, though not directly. The read/write capability is given to istream/ostream through the virtual base class ios.

Both fstreambase and istream/ostream are derived from ios. Since it is a virtual derivation, both of the classes share the same copy of ios's data members. Among these members are a pointer to a streambuf type. fstreambase gives ios a pointer to its filebuf object during initialization. During use, istream/ostream uses this pointer to access the filebuf for reading and writing. The ios class also has various format and state flags and numerous functions for setting and reading these flags.

The filebuf class is the workhorse of the hierarchy. It is the one that actually calls for reads and writes from the file. It also handles opening, closing, seeking, and buffering. When an fstream is opened, the fstream-base open function calls filebuf's open which calls the global open. The filebuf class is derived from streambuf.

The streambuf class is an abstract type that allows ios to communicate with different types of buffer classes. Since ios contains a pointer to a streambuf type it can communicate with filebuf through virtual functions. The virtual functions overflow, underflow, seekoff, setbuf, and sync provide ios and istream/ostream the ability to read, write, and seek.