Deriving from ostream...

I'm interested in writing a class, derived from ostream or cout or something in that family, which will receive output data in exactly the same way as a cout or ofstream object would. (using the insertion ['<<'] operator)

My class will then pass the same data to both cout and a previously defined ofstream object, so that any text, numbers, etc I wish to output I can perform simultaneous screen and file printing.

I've already implemented these concepts in a few template functions I've created but it's not as natural as using the "stream << ouput" syntax and requires the additional work of sprintf'ing any variable-inclusive strings I wish to output.

If anyone knows how to perform such a feat (or has another way of performing it and getting the same results) please either post back here, or, preferably, email me at thynctank@metro-bands.com

You could make a class that inherits ofstream and ifstream then overload its left and right bitshift operators (<< and >>) so that you can do whatever you want. If you could post what you have of your class I can tell you where you need to put some code.

Minimal existing code

Hey master5001.

I'm a real casual programmer, haven't been using C++ for all that long. So I'm not really certain how to begin deriving myself a class of this sort, though I know it can be done. (as cout is a derived class of ostream itself)

Basically, my existing code is merely what is required to derive from ostream. Something like:

class output: public ostream
{
public:
//NOT SURE how to implement the ostream constructor
output(streambuf* psb) { cout << psb; outfile << psb; }
/*
constructor sig according to the little documentation I've found and outfile is an ofstream object predefined in a namespace open()ed in implementation program so that file can be specified there, where it's more appropriate
*/
~output();
};

I might need to redefine a whole slew of operator <<'s for the various data types I'll be sending to it, and if I send custom objects directly to it I realize I'll have to overload there <<'s as well.

I have no clue as to how to finish this off, or even for certain that I'm going about it the correct way. The syntax I'd like to use once an object of type output is created is this:

outputobject << "Text and then " << x << 32 << 'c';

In other words, I'd like my output class to behave syntactically exactly like cout or an ofstream, in that it accepts incoming streams composed of numbers, C-strings, characters and so on.

I only really intend to send basic data types to output, but I'm fairly lost at this point and if you could just point me to a reference or anything along those lines it'd be good.