Rebind template(bug?)

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 21 12:42:08 PDT 2016


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)
}



More information about the Digitalmars-d-learn mailing list