Arrays of Unions of Classes?

tcak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 6 11:10:54 PST 2015


On Friday, 6 February 2015 at 18:55:30 UTC, DLearner wrote:
> I'm just wondering how I would go about reserving a section of
> the heap so I can have linear access to classes of different
> types. Storage space--not too worried about wasting; each class 
> I
> want to store only has a few int sized variables each and I'm 
> not
> going to cry over a little padding.
>
> Because classes are reference types, does that mean a union or 
> an
> array would only hold a reference to that class? Is there a way
> for them to be squished up next to each other in a way that'd
> make iterating over them efficent? I could do this with structs
> (at least I think I can in D) except they're not polymorphic and
> structs don't remember their type internally like classes do 
> when
> inside unions (I just tested this, I assume it's a feature not a
> bug?).
>
> I have a lot of elements in an array that I need to pass over
> constantly so if I can not break them up and not have to make up
> pretend internal polymorphism with switch statements inside
> functions then that'd both make my code look less like spaghetti
> and leave room for me to bog down my program with other crap. 
> How
> do I do this in D?


Let's say you have a class with name "MyClass".


You create an array with that:

MyClass[64] myClassList;


Then you have created objects in this array:

myClassList[0] = new MyClass();
myClassList[1] = new MyClass();
myClassList[2] = new MyClass();
...


Now you have linear access to objects in this array:

myClassList[2].setIntValue( 7 );


What is the necessity for these objects in heap to be consecutive?


More information about the Digitalmars-d-learn mailing list