Rebind template(bug?)
Engine Machine via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 21 13:36:54 PDT 2016
On Sunday, 21 August 2016 at 19:42:08 UTC, Lodovico Giaretta
wrote:
> On Sunday, 21 August 2016 at 19:29:26 UTC, Engine Machine wrote:
>> [...]
>
> The problem of this code has nothing to do with aliases. They
> work correctly. The problem is variable shadowing. In the
> following code, Child has two x variables, one of which is only
> accessible from a Parent reference, the other only from a Child
> reference.
>
> class Parent
> {
> int x;
> }
> class Child: Parent
> {
> int x; // this shadows Parent.x
> int y;
> }
>
> void main()
> {
> Child child = new Child();
> Parent parent = child;
>
> child.x = child.y = 3;
> parent.x = 2;
>
> assert(child.x == 3);
> assert((cast(Child)parent).x == 3);
> assert((cast(Parent)child).x == 2);
>
> assert(parent is child); // same object (remember that a
> class is already a pointer);
> assert(&parent != &child); // but there are two different
> pointers on the stack (pointing to the same object)
> }
You're right. I didn't realize that variables could be shadowed
in classes. Seems dangerous. D doesn't allow shadowing in a
normal context and gives an error so I don't know why it wouldn't
do that in classes. (since it wasn't giving an error I thought it
wasn't shadowing)
More information about the Digitalmars-d-learn
mailing list