Rogue Wave banner
Previous fileTop of DocumentContentsIndexNext file

17.3 Construction and Initialization

All standard stream classes have class basic_ios<charT,Traits> as a virtual base class. In C++, a virtual base class is initialized by its most derived class; that is, our new odatstream class is responsible for initialization of its base class basic_ios<charT,Traits>. Now class basic_ios<charT,Traits> has only one public constructor, which takes a pointer to a stream buffer. This is because class basic_ios<charT,Traits> contains a pointer to the stream buffer, which has to be initialized when a basic_ios object is constructed. Consequently, we must figure out how to provide a stream buffer to our base class. Let's consider two options:

17.3.1 Derivation from File Stream or String Stream Classes Like (i/o)fstream<> or (i/o)stringstream<>

The file and string stream classes contain a stream buffer data member and already monitor the initialization of their virtual base initialization by providing the pointer to their own stream buffer. If we derive from one of these classes, we do not provide another stream buffer pointer because it would be overwritten by the file or string stream's constructor anyway. (Remember that virtual base classes are constructed before non-virtual base classes regardless of where they appear in the hierarchy.) Consider:

The order of construction would be:

In other words, the constructor of basic_ofstream overwrites the stream buffer pointer set by the constructor of basic_ios.

To avoid this dilemma, class basic_ios<charT,Traits> has a protected default constructor in addition to its public constructor. This default constructor, which requires a stream buffer pointer, doesn't do anything. Instead, there is a protected initialization function basic_ios<charT,Traits>::init() that can be called by any class derived from basic_ios<charT,Traits>. With this function, initialization of the basic_ios<> base class is handled by the stream class that actually provides the stream buffer-in our example, basic_ofstream<charT,Traits>. It calls the protected init() function:

The order of construction and initialization is:

17.3.2 Derivation from the Stream Classes basic_(i/o)stream<>

The scheme for deriving from the stream classes is slightly different in that you must always provide a pointer to a stream buffer. This is because the stream classes do not contain a stream buffer, as the file or string stream classes do. For example, a class derived from an output stream could look like this:

There are several ways to provide the stream buffer required for constructing such a stream:


Previous fileTop of DocumentContentsIndexNext file

OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.