Best way to reference an array in a child class...
Ali Çehreli
acehreli at yahoo.com
Thu Mar 6 14:28:19 PST 2014
On 03/06/2014 02:05 PM, captain_fid wrote:
> 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?
Yes, but it also depends on the need. I assumed that the base class
needed a slice of elements from the base class.
Will the slice of elements ever change? If no, then the base could take
them at construction time and use them in the future:
import std.stdio;
class B
{
const(int[]) items;
this(const(int[]) items) // <-- Requires elements
// during construction
{
this.items = items;
}
final void do_work()
{
writeln(items);
}
}
class D : B
{
this()
{
super([ 1, 2, 3]); // Items are determined here
}
}
void main()
{
auto d = new D();
d.do_work();
}
Alternatively, and especially if the elements will change at run time,
the derived class can hold on to the elements and can provide them as
the base class needs:
import std.stdio;
class B
{
abstract const(int)[] items();
final void do_work()
{
writeln(items());
}
}
class D : B
{
int[] myItems;
this()
{
myItems = [ 1, 2, 3];
}
void add(int[] items)
{
myItems ~= items;
}
override const(int)[] items()
{
return myItems;
}
}
void main()
{
auto d = new D();
d.do_work(); // 1, 2, 3
// Add more later on
d.add([ 4, 5, 6 ]);
d.do_work(); // 1, 2, 3, 4, 5, 6
}
Ali
More information about the Digitalmars-d-learn
mailing list