Hey, I'm trying to create a class that's derived from ostringstream. So, it's like this:
class Message2:public ostringstream {
public:
Message2 *flush();
};
My flush command does some special stuff, but the problem is it's never called! I've tried setting unitbuf (message << unitbuf; - is that the right way?), but that doesn't improve anything. Ending my streams with endl or flush doesn't call it either. So what's going on here?
Name:
Anonymous2007-03-23 22:26 ID:HEGPlAzY
I don't know C++ (it fails), but maybe it has something to do with virtual methods (or rather not being virtual)?
What exactly are you trying to accomplish? You can change the behavior of flush by writing a subclass of basic_streambuf (or basic_stringbuf) which does have virtual methods. Then create a subclass of basic_ostream which uses that buffer class.
Name:
Anonymous2007-03-24 7:39 ID:oAWpGC3k
maybe it's clogged or something
Name:
Anonymous2007-03-24 8:50 ID:H0aXEwQB
Sounds like he's trying to override ostringstream::flush() so that when it automatically flushes, it calls _his_ version, not the base class' version.
Message2 Message2::flush()
{
ostringstream::flush(); //MUST call parent function first
//and then do your stuff
printf("special stuff\n");
; //special stuff
; done here
; //then create your Message2 object and
Message2 temp;
return temp;
}
Please correct my "return message2" part if there's a less strange way to do it.
Name:
Anonymous2007-03-25 3:12 ID:l+cv0ziO
Agh. My code looked horrid. Anyway, sometimes code such as in the line with ostringstream::flush() needs some casting, I recall. Like if your object is dynamically allocated, it might need to go like
((ostringstream) *this ).flush();
in order to dynamically convert the current object to the parent type, which then forces flush to use the parent function.
Name:
Anonymous2007-03-26 9:33 ID:wTlOzUkI
That's what happen with bad OO models. Why the fuck would you NOT want methods to be virtual? I mean, that's the fucking point! (If you inherit and override from some class and your method is not compatible with what it overrieds, then reimplement the rest of the class or don't fucking write it!)
Name:
Anonymous2007-03-26 10:21 ID:vTlgTNIS
>>8
That's because the ostream class just formats the output e.g. convert an integer to string. Then it sends this string to a subclass of streambuf. The streambuf subclass can then write the output to a file (filebuf), write it to a string (stringbuf), etc. So if you want to change the behavior of flush you should create a subclass of streambuf, which has been carefully designed to include virtual methods.
For example:
class messagebuf : public stringbuf {
protected:
virtual int sync() {
cout << "stream has been flushed\n";
return 0;
}
}
Then use it like this:
messagebuf buf;
ostream out(&buf);
out << "y helo thar" << endl;