Why D const is annoying

Jacob Carlborg doob at me.com
Wed May 2 11:23:03 PDT 2012


On 2012-05-02 18:01, Mehrdad wrote:
>> When you're making the object 'const', you're not making the
>> assumption that no one who derives from this class need mutable state.
>> What you're doing is asserting that bits belonging to this object
>> needs to be 'const' to preserve sequential consistency across threads
>> or for other reasons.
>
> Bits belonging to *this* object? I thought const was transitive...
>
>> If the derived class casts away const, it breaks that contract.
>
> So you're saying the same thing: Derived classes CANNOT have mutable
> state...

No:

interface Foo
{
     void foo () const;
}

class Bar : Foo
{
     int x;

     void foo () const {}

     void bar ()
     {
         x++;
     }
}

void main()
{
     auto bar = new Bar;
     bar.bar();
     writeln(bar.x);
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list