Reputation: 1103
while studying I/O
I came across:
iostream: istream reads from a stream, ostream writes to a stream, iostream reads and writes a stream: derived from istream and ostream
What is the need of inheritance if istream
and ostream
do the same job?
Upvotes: 0
Views: 301
Reputation: 1272
The prototypes for a writer and reader are
class MyClass;
std::ostream& operator<< (std::ostream stream&, const MyClass &obj)
{
obj->WriteTo(stream);
return stream;
}
std::istream& operator>> (std::istream stream&, MyClass &obj)
{
obj->ReadFrom(stream);
return stream;
}
These functions (especially the writer) call lower-level stream functions on MyClass
'es members.
Having std::iostream
derived from both std::istream
and std::ostream
means that you can pass an instance of std::iostream
to either function and it automatically pass in the correct part of std::iostream
in.
std::istream
and std::ostream
are statically derived from std::ios
which contains the common code for them.
Upvotes: 1
Reputation: 16726
Exactly by making iostream
inherit from istream
and from ostream
you get a class that supports input and output and both interfaces (from istream
and ostream
). That doesn't mean that functionality is duplicated, it just means that the interfaces of istream
and ostream
and their implementation is being reused.
Upvotes: 1