Why is it not possible to write to a file from a const member function ?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 12 07:32:39 PST 2016


On Saturday, 12 March 2016 at 14:02:31 UTC, user42 wrote:

> Why is this thing not compiling ?
> Or, in other words, how is is possible to log something to a 
> file from a const member function ?
>

Const member functions functions are not allowed to mutate any 
member state at all. This includes the state of any object 
instances that are members. Since the write method of the File 
type is not declared as const, then you can not call it on a 
member of type File from inside a const member function. Logging, 
by its very definition, mutates state.

Move the File instance outside of the class and it works.

import std.stdio;
private File f;
static this() { f = stdout; }

class X
{
   void p(string s) const
   {
      f.writeln!(string)(s);
   }
}

class Y
{
   private string s = "Y";

   override string toString() const
   {
      return s;
   }
}

void main()
{
   auto x = new X;
   auto y = new Y;

   import std.conv: to;
   x.p(to!string(y));
}


More information about the Digitalmars-d-learn mailing list