Why << operator in ofstream is not const?

812 views Asked by At

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?

3

There are 3 answers

0
SergeyA On BEST ANSWER

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.

0
msaw328 On

Keep in mind that while ofstream itself doesn't have to be modified to be written to (even though it probably should), the ostringstream which also inherits the << operator from ostream class has to be modified in order to be written to, as you need to change the internal string object. Because of that, the operator has to be declared const to cover all the cases (the operator is defined in ostream class).

0
Hatted Rooster On

Because it may call setstate() which isn't const for a reason since it changes the internals of the object as noted in the formatting part for streams.