hijacking a class's members

Rory Mcguire rjmcguire at gm_no_ail.com
Wed Aug 4 07:00:31 PDT 2010


Mafi wrote:

> Am 04.08.2010 12:11, schrieb Rory Mcguire:
>> Hi,
>>
>> The code below is my beginning to attempt a class which implements any
>> class and throws an exception if one tries to access any member of that
>> class.
>>
>> Problem is that if I use:
>> auto a1 = noinit!(A)();
>>
>> it works and accesses the int x() {...} member of the generated class,
>> but if I use:
>> A a1 = noinit!(A)();
>>
>> it accesses A.x instead of the generated classes x.
>>
>> So am I wrong in making a sub class have a member function which hides a
>> parent class's member variable or is the compiler wrong and it should
>> generate a call to generated sub class?
>>
>>
>> Thanks!!!
>> -Rory
> Hi,
> if x is a field (ie a member variable) it's statically bound. In your
> example it is a field so it gets A.x of your subclass which is still
> there becuase of the methoda of A which could use A.x.
> Fields have to be statically bound because there's no covariance
> guarateed with them. Use getters and setters instead.
> BTW are @propertys statically or dynamically bound. They're kind of
> both: fields and methods.
> 
> Mafi

Thats what feels weird to me. a.x can result in different things happening 
even though x exists in both A and the generated class. However the 
generated class has two "fields" called x one you can't access anymore and 
the @property one.
When I create an instance of the generated class I would expect it to always 
to the same thing if I use one of its methods/properties/etc...
Kind of like you would expect the following to print out "hello 2":
class A {
    string toString() { return "hello"; }
}
class B : A {
    string toString() { return super.toString() ~ " 2"; }
}
void main() {
    A a = new B();
    writeln(a.toString()); // uses B.toString()
}

What I've got is:
class A {
    int x;
}
class B : A {
    int x() { throw new Exception(); }
}
void main() {
    A a = new B();
    writeln(a.x); // this accesses A.x not B.x!!!!
}

just seems like properties are not quite right or something.

-Rory



More information about the Digitalmars-d-learn mailing list