digitalmars.D - Class field inheritance
- André Wagner (23/23) Jun 30 2010 Hello,
- Adam Ruppe (5/5) Jun 30 2010 Easy one: xa is null. This one used to bite me all the time too, since
- André Wagner (23/23) Jun 30 2010 Ok, bad example :)
- Simen kjaeraas (7/30) Jun 30 2010 That would be because B.j hides A.j. A's constructor sets
Hello, I have code that has the following structure: class XA { uint x; } class XB : XA { uint y; } class A { XA xa; this() { xa.x = 2; } } class B { XB xa; this() { xa.x = 3; xa.y = 4; } } void main() { B b = new B(); } When I run, the statement that says "xa.x = 3" halts with "object.Error: access violation". Why? If I add "uint x" to XB, I get the same error. If I change the name of "xa" in the class "B", I also get the same error. I couldn't find anything in the documentation that explains how D deals with fields in inherited classes. I'm using D2. Regards, André
Jun 30 2010
Easy one: xa is null. This one used to bite me all the time too, since I was used to C++ where XA xa; works on its own. But in D, classes are always created by reference (think of them all as pointers), so you have to new them before using them. Just add an xa = new XA; to your constructor and it will work out.
Jun 30 2010
Ok, bad example :) Here's a better example of what I wanted to ask: class XA { uint x; } class XB : XA { uint y; } class A { XA j; this(XA j) { this.j = j; } } class B : A { XB j; this(XB j) { super(j); } } void main() { XB j = new XB(); j.x = 10; j.y = 20; B b = new B(j); writefln("%d\n", b.j.x); } Why doesn't this work?
Jun 30 2010
Andr=C3=A9 Wagner <andre.nho gmail.com> wrote:Ok, bad example :) Here's a better example of what I wanted to ask: class XA { uint x; } class XB : XA { uint y; } class A { XA j; this(XA j) { this.j =3D j; } } class B : A { XB j; this(XB j) { super(j); } } void main() { XB j =3D new XB(); j.x =3D 10; j.y =3D 20; B b =3D new B(j); writefln("%d\n", b.j.x); } Why doesn't this work?That would be because B.j hides A.j. A's constructor sets B.super.j, not B.j. If you try in your main, writeln( cast( A )( b ).j.x );, you will see that A.j is set correctly. -- = Simen
Jun 30 2010