Hi.
I'm having a hard time understanding D's inheritance. Consider
the following code:
class Parent {
public int x = 10;
}
class Child : Parent {
public int y = 20;
}
void main() {
import std.stdio;
Parent[] array;
auto obj1 = new Parent();
auto obj2 = new Child();
array ~= obj1;
array ~= obj2;
writeln(array[0]); // prints "Parent", as expected
writeln(array[1]); // prints "Child", so I assume that if
it's a Child, we can access Child's fields
writeln(array[0].x); // 10
writeln(array[1].y); // Error: no property 'y' for type
'Parent'
}
First, I don't understand why we see array[2] as 'Child'. While
it is a 'Child', shouldn't it be shown as a 'Parent' due to we
explicitly create an array of 'Parents'?
Well, if it's still a 'Child', why we can't access it's fields?
And what is the proper way of storing a collection of inherited
objects without losing access to their fields and methods?
Please point me in the right direction. I'm (still) relatively
new to D, and will appreciate any help.