Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why fstream is not inherited from ifstream and ofstream in c++?

ifstream and ofstream is for input and output in file, and fstream can do task of both them but not inherited from either of ifstream and ofstream, is this code repetition or something else?

Hierarchy of fstream

like image 961
Onk_r Avatar asked Jun 12 '18 12:06

Onk_r


People also ask

What is the difference between ifstream and ofstream and fstream?

ifstream is input file stream which allows you to read the contents of a file. ofstream is output file stream which allows you to write contents to a file. fstream allows both reading from and writing to files by default.

Does istream inherit from ifstream?

File streams are a lot like cin and cout File streams come in two flavors also: the class ifstream (input file stream) inherits from istream, and the class ofstream (output file stream) inherits from ostream.

Which class is the base class for fstream ifstream and ofstream?

The I/O system of C++ contains a set of classes which define the file handling methods. These include ifstream, ofstream and fstream classes. These classes area derived from fstream and from the corresponding iostream class.

Is fstream included in iostream?

An fstream is an iostream which writes to and reads from a file. So: every fstream is an iostream but not every iostream is an fstream.


1 Answers

You'd have to ask the author, Bjarne Stroustrup, for a definitive answer. In his original paper on iostreams published in USENIX Proceedings of 1985, he seems to put a lot of emphasis on efficiency:

Inline expanded functions are used for the basic operations (like "put a character into a buffer"), so the basic overhead tend to be one function call per simple object (integer, string, etc.) written (or read) plus one function call per buffer overflow.

So that could be the reason.

I guess you could extract common file I/O functionality into a mixin, but that would require virtual inheritance in order to allow for the diamond inheritance, which would add an extra indirection when accessing the underlying basic_filebuf.

In addition, as a file read/write mode normally cannot be changed once the file is opened, being able to cast fstream to ifstream or ofstream would create inconsistencies as you could get a writable ifstream or a readable ofstream.

like image 97
rustyx Avatar answered Sep 21 '22 08:09

rustyx