I've been googling around and I just can't find a simple answer to this. And it should be simple, as the STL generally is.
I want to define MyOStream which inherits publicly from std::ostream. Let's say I want to call foo() each time something is written into my stream.
class MyOStream : public ostream {
public:
...
private:
void foo() { ... }
}
I understand that the public interface of ostream is non-virtual, so how can it be done? I want clients to be able to use both operator<< and write() and put() on MyOStream and have use the extended ability of my class.
It's not a simple question, unfortunately. The classes you should derive from are the basic_
classes, such as basic_ostream
. However, derivation from a stream may not be what you want, you may want to derive from a stream buffer instead, and then use this class to instantiate an existing stream class.
The whole area is complex, but there is an excellent book about it Standard C++ IOStreams and Locales, which I suggest you take a look at before going any further.