Readonly class members

Kristian kjkilpi at gmail.com
Thu Sep 14 08:03:35 PDT 2006


On Thu, 14 Sep 2006 16:59:56 +0300, 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.

Well, when I said that this woundn't be needed in D, I didn't realize the  
fact that will reduce the amount of written code, a little (no need to  
write a read property). So maybe there is a demand for such a feature in D  
after all...

In addition, what if it would be possible then to have a write property  
using the same name? For example:

class Obj {
     int size(int newSize) {
         return(size = newSize);
     }

     readonly int size;
}

void func() {
     Obj o = new Obj;
     int v;

     v = o.size;  //variable used
     o.size = 1;  //function 'size()' used
}

Defining a read function woundn't be possible, I think, so the 'read  
access' couldn't be overridden. The 'size' variable should then hold a  
cached value, so to speak. (When the size value is changed in the class,  
the 'size' variable is updated correspondingly.)

I am not sure if this is a good idea or not. For instance, if you write  
"size = 1;" _inside_ the class, should the function be called or the  
variable modified directly? If the function is used, how to access the  
variable, etc. So, apparently, the function should be only used outside  
the class. It'll notify that the user wants to change the value.



More information about the Digitalmars-d mailing list