Best way to reference an array in a child class...

Ali Çehreli acehreli at yahoo.com
Thu Mar 6 11:44:40 PST 2014


On 03/06/2014 11:31 AM, captain_fid wrote:
> On Thursday, 6 March 2014 at 19:19:29 UTC, captain_fid wrote:
>> Sorry for the very basic question. Much still alludes me with this
>> language. I appreciate the forum.
>>
>> struct S
>> {
>
> Wow sorry for that. I'm a moron... don't press <tab> <enter>...
>
> struct S
> {
>    int a;
>    string b;
> }
>
> class A
> {
>    S[]* pointer_to_list;
>    abstract...
> }
>
> class B: A
> {
>    S[] items = [ {10, "first"}, {20, "second"}];
>
>    this() {
>     pointer_to_list = &items;
>    }
> }
>
> My problem is in de-referencing later (seg fault). Is this even the best
> way?
>
> I Really need to access the array in a derived class. 'S' (I believe)
> really is best as a Structure.
>
> Any suggestions. Thanks in advance (and sorry for the rough start).
>
>

You need to dereference the pointer by * and you would be using a slice:

import std.stdio;
import std.conv;

struct S
{
     int a;
     string b;
}

class A
{
     S[]* pointer_to_list;

     void access()
     {
         foreach (e; *pointer_to_list) {    // <-- NOTE *
             writeln(e);
         }
     }
}

class B: A
{
     S[] items = [ {10, "first"}, {20, "second"}];

     this() {
         pointer_to_list = &items;
     }
}

void main()
{
     auto b = new B();

     foreach (i; 30 .. 40) {
         b.items ~= S(i, i.to!string);
     }

     b.access();
}

As a side note, I would make A take the slice as a reference parameter, 
rather that B accessing A's member directly. It is better for 
maintainability:

class A
{
     S[]* pointer_to_list;

     this(ref S[] list)    // <-- BETTER
     {
         this.pointer_to_list = &list;
     }

// ...
}

class B: A
{
// ...

     this() {
         super(items);    // <-- BETTER
     }
}

Ali



More information about the Digitalmars-d-learn mailing list