Readonly class members
Kristian
kjkilpi at gmail.com
Fri Sep 15 04:48:08 PDT 2006
On Fri, 15 Sep 2006 04:40:11 +0300, Chris Miller <chris at dprogramming.com>
wrote:
> On Thu, 14 Sep 2006 09:59:56 -0400, Georg Wrede <georg.wrede at nospam.org>
> wrote:
>
>>> From time to time I wish that C++ would have a readonly specifier
>>> that works like this:
>>> class Obj {
>>> void f() {
>>> int m_size = 10; //ok
>>> }
>>> readonly int m_size;
>>> }
>>> void func() {
>>> Obj o = new Obj;
>>> int v;
>>> v = o.m_size; //ok
>>> o.m_size = 5; //error
>>> }
>>
>>> 'm_size' can be accessed inside 'Obj' as normal, but outside the class
>>> the variable cannot be modified. Of course, I could provide a read
>>> property (that is, a function in C++) for accessing 'm_size' (in
>>> addition to a write property), but when it's not necessary, this way is
>>> simplier (and a little bit faster, etc.).
>>> In D this, however, is not needed because you can use properties to
>>> wrap
>>> member variables.
>>> (Hopefully the properties will be extended to support the same methods
>>> that can be applied to variables also... ;) )
>>
>> Hmm. IMHO, this would be very easy to implement in the compiler. It
>> would make class definitions clearer, and in many cases would lessen
>> the need to write code.
>>
>> Just off-hand I can imagine quite a few situations where I'd use this.
>
> D's const has this ability..
> class Obj
> {
> this(int foo) { m_size = foo; }
> const int m_size;
> }
If I am not completely mistaken here, you're mistaken. ;)
One can use 'const' as you demostrated, but 'm_size' can be set only in
constructor(s) to initialize it. A 'readonly' variable would be assignable
everywhere inside 'Obj' (but only inside the class). That is, it's public
for reading and protected for writing.
More information about the Digitalmars-d
mailing list