Readonly class members
Kristian
kjkilpi at gmail.com
Sat Sep 16 02:09:31 PDT 2006
On Sat, 16 Sep 2006 00:22:12 +0300, Jarrett Billingsley
<kb3ctd2 at yahoo.com> wrote:
> "Georg Wrede" <georg.wrede at nospam.org> wrote in message
> news:4509605C.3040408 at nospam.org...
>
>>> 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
>>> }
>
>> 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.
>
> class Obj
> {
> void f()
> {
> int mSize = 10;
> }
>
> public int size()
> {
> return mSize;
> }
>
> private int mSize;
> }
>
> ..
>
> Obj o = new Obj;
> o.f();
> writefln(o.size);
> o.size = 4; // illegal
>
> Properties, broperties.
Yep, you're right. However, I think you miss the point of this thread by a
little... ;)
In the very first post (the quoted part) I said that this feature isn't
needed in D because of the properties. Then Georg pointed out that it
would lesses the need to write code (no need to create a read property).
Then I stated that this feature is faster also so that it could be useful
in some time critical cases.
Few hours ago ephemeros send a message "Properties set/get huge speed
difference?" to digitalmars.D.learn. He was wondering why a read property
is so much slower (about 20 times) than accessing directly a member
variable. (That's because a virtual function call is slower than accessing
a variable, of course.)
If this feature, lets call it "sub-property", would be possible, then
reading a property value will always be *very* fast (just access a
variable).
And if my another thought, a write property using the same name as the
member variable, would be possible, then you could use it just like normal
properties (that is, outside the class).
For example:
class Obj {
void f() {
size = 10; //ok; use member variable
}
int size(int newSize) {
return(size = newSize); //use member variable
}
readonly int size;
}
void func() {
Obj o = new Obj;
int s;
s = o.size; //use member variable
o.size = 1; //use write property
}
Of course, this creates an ambiguous situation in 'Obj': a function and a
variable uses the same name. So, variable should overrule a write property
inside the class.
More information about the Digitalmars-d
mailing list