oop tutorials

Jesse Phillips jessekphillips at gmail.com
Tue Mar 4 13:22:57 PST 2008


Just so you can ask that question, no not really but I'll tell you the 
difference.

auto store = new Bike[10];

Allocates memory on the heap, which means the function can return it.

Bike[10] store;

will allocate memory on the stack thus will not exist when the function 
returns. I had no reason not to use this, I just ended up not.

And both arrays are static, thus there length will not change.

A note to your other reply, you are correct, that was what I meant.

On Tue, 04 Mar 2008 18:19:47 +0100, Saaa wrote:

> Thanks.
> 
> Why did you use:
>     auto store = new Bike[10];
>     store[] = new Bike(null);
> iso:
>     Bike[10] store;
>     store[] = new Bike(null);
> 
> At first I thought that:
>     auto store = new Bike[10];
> would allocate the instances as well.
> 
> 
>> class Bike {
>>    Human owner;
>>
>>    this(Human o) {
>>         owner = o;
>>    }
>>    public void newOwner(Human o) {
>>         owner = o;
>>    }
>> }
>>
>> class Human {
>>    Bike bike;
>>    char[] name;
>>
>> public:
>>   this(char[] n) { name = n; }
>>
>>    void ride() {
>>         if(bike !is null) {
>>             writefln("%s is riding his bike", name);
>>         }
>>    }
>>
>>    void purchase(Bike b) {
>>         b.newOwner(this);
>>    }
>> }
>>
>> void main() {
>>    auto store = new Bike[10];
>>    store[] = new Bike(null);
>>
>>    Human joe = new Human("Joe");
>>    joe.ride();
>>
>>    // Joe buys a new bike
>>    joe.purchase(store[4]);
>> }
>>
>> you will notice that the bike requires an owner, but I provided none
>> during creation. Also note that a Human does not have to own a bike,
>> would you want to force a creation of bike even though he has not
>> purchased one? I didn't test the code, but I hope it works.
>>
>> One of the things that happens as that you want a reference to an
>> object type, but not create a new one, because later you will be
>> getting the reference from somewhere else. Feel free to use what I have
>> given you.


More information about the Digitalmars-d-learn mailing list