Search code examples
c++fstreamiostreamofstream

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


Solution

  • 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.