www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Class field inheritance

reply André Wagner <andre.nho gmail.com> writes:
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
parent reply Adam Ruppe <destructionator gmail.com> writes:
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
parent reply André Wagner <andre.nho gmail.com> writes:
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
parent "Simen kjaeraas" <simen.kjaras gmail.com> writes:
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