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

captain_fid bell.hue at gmail.com
Thu Mar 6 14:32:05 PST 2014


On Thursday, 6 March 2014 at 22:16:50 UTC, Steven Schveighoffer 
wrote:
> On Thu, 06 Mar 2014 17:05:12 -0500, captain_fid 
> <bell.hue at gmail.com> wrote:
>
>> On Thursday, 6 March 2014 at 21:26:11 UTC, Ali Çehreli wrote:
>>> On 03/06/2014 12:02 PM, Steven Schveighoffer wrote:
>>>
>>> > The best way
>>> > to reference an array in a child class, especially one of a
>>> static type,
>>> > is to not have another copy in the child class :)
>>>
>>> Agreed. Alternatively, a member function in the child class 
>>> could return a slice.
>>>
>>> Ali
>>
>> Steve, thanks for the link and the nicely written article. 
>> Also for the assessment on pointer syntax, I'd love to avoid 
>> if possible (especially w/ limitations you noted).
>>
>> I had been spending time over at http://dlang.org/arrays.html 
>> and had forgotten (or never understood) dynamic arrays were 
>> passed by slices. That link only talks about passing static 
>> arrays (IIRC). Keeping track of 'what being passed how' is 
>> tough for this programmer.
>>
>> Your suggestion Ali (of not accessing the base member in the 
>> child was great) and it works properly.
>>
>> Believe if I understand what you are suggesting above is never 
>> to have the array in base? simply retrieve slice through the 
>> child member function?
>
> I think what Ali means is:
>
> class A
> {
>    abstract S[] items();
> }
>
> class B : A
> {
>    S[] _items = [ {10, "first"}, {20, "second"}];
>    override S[] items() { return _items;}
> }
>
> What I was saying is, if you know the items are going to be 
> stored in the object, just store them in the base:
>
> class A
> {
>     S[] items;
> }
>
> class B : A
> {
>     this() {items = [ {10, "first"}, {20, "second"}];}
> }
>
> This way, both the derived and the base will always see the 
> same items, and you only store it in the object once. Obviously 
> if you store the items elsewhere in some derivatives, Ali's 
> idea is preferable.
>
> -Steve

Yes Steve!

Even if the title of the thread is off, the original intent was 
what you've shown. For a reason (probably duplicate definitions 
in base and child) I would end up with items in B and not visible 
in A.

I didn't understand the syntax for performing the above.

I owe you guys a beer (or something). Definitely a learning 
lesson.


More information about the Digitalmars-d-learn mailing list