Search code examples
c++ofstream

Why << operator in ofstream is not const?


I noticed that the operator << in ofstream is not const. It is obvious that this operator will change the content of the file but what is it changing inside the ofstream object?

In other words, if I have ofstream as a class member function and I want to call the << operator on it inside a const member function I have to alter it to non-const member function or mark the ofstream as mutable but it seems not logical from abstract point of view for me.. did I miss something?


Solution

  • Because it logically changes the stream. To the bare minimum, it changes the write position within the stream buffer. It can also modify the status of the stream (for example, when writing error happens).

    But what is even more important (in my view) is the logical mutability. The stream is not the same after the writing - it has the new value in it. If your class doesn't care about this fact, you may declare your stream member mutable.