News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ Tips: IO - no virtual inserters and extractors?

Started by ben2ong2, October 06, 2006, 11:23:16 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

(Newsgroups: comp.std.c++, 3 Mar 97)


[ Terminology: inserter = operator<< ()
               extractor = operator>> ()  -adc ]


MARIAN: "marian" <marian@shellx.best.com>

>I heard that they considered making inserters and extractors virtual
>in iostreams. 
>   Why was this suggested?
>   Why was this not done?


CLAMAGE: You are not allowed to view links. Register or Login (Steve Clamage)

The question about virtual inserters/extractors comes up from time
to time, and indeed it was discussed at least once by the library
working group within the C++ committee.

The main argument in favor of making them virtual is to allow
you to derive a class from istream or ostream and get polymorphic
behavior. Iostream functions accept or return references to istream
or ostream, not to my_istream or my_ostream, and without the virtual
functions, derivation doesn't have the right behavior.

Interestingly, the argument *against* making them virtual is the same.
Suppose I write an extractor for MyClass:

   ostream& operator<<(ostream& o, const MyClass& m) {
      o << '[' << m.data1 << '\t' << m.data2 << ']';
      return o;
   }

Because inserters are not virtual, I know exactly what the output format
will look like, and in particular I know that any extractor I write can
can depend on reading that format. If inserters were virtual, I could not
depend on the output format, nor write an extractor that would be sure to work.

Clearly, these arguments can go around and around. The original design
of iostreams made the functions non-virtual, meaning that you usually
don't derive from istream or ostream for the purpose of getting different
inserter/extractor behavior. The C++ committee decided not to
change that basic design decision.
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login