| Thread overview | ||||||
|---|---|---|---|---|---|---|
|
June 30, 2010 Class field inheritance | ||||
|---|---|---|---|---|
| ||||
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é
| ||||
June 30, 2010 Re: Class field inheritance | ||||
|---|---|---|---|---|
| ||||
Posted in reply to André Wagner | 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. | |||
June 30, 2010 Re: Class field inheritance | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Adam Ruppe | 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?
| |||
June 30, 2010 Re: Class field inheritance | ||||
|---|---|---|---|---|
| ||||
Posted in reply to André Wagner | André 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 = 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? 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 | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply