oop tutorials

Saaa empty at needmail.com
Tue Mar 4 09:19:47 PST 2008


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