oop tutorials

Ty Tower tytower at hotmail.com.au
Fri Mar 7 20:45:29 PST 2008


Jesse Phillips Wrote:

> On Fri, 07 Mar 2008 07:11:48 +0100, Saaa wrote:
> 
> >>    auto store = new Bike[10];
> >>    store[] = new Bike(null);
> > 
> > Would anything change if I would replace those two lines with:
> > 
> > Bike[10] store;
> > 
> > (It compiles, runs and outputs the same)
> > 
> > Because I read those two lines as:
> >> Allocate memory for 10 bikes
> >> free the memory
> 
> umm, yes. The first line is allocating the memory to store Bikes on to 
> the heap. Your suggested line will do the same, but on the stack.
> 
> Where the problem comes is if you remove the second line. Here's a 
> modification to show that. Try it with and without the line, I'll explain 
> below.
> 
> class Bike {
>     Human owner;
>     char[] type;
> 
>     this(Human o, char[] t) {
>          owner = o;
>          type = t;
>     }
>     public void newOwner(Human o) {
>          owner = o;
>     }
>     public void ride() {
>          writefln("riding his new %s bike", type);
>     }
> }
> 
> class Human {
>     Bike bike;
>     char[] name;
> 
> public:
>    this(char[] n) { name = n; }
> 
>     void ride() {
>          if(bike !is null) {
>              writef("%s is", name);
>              bike.ride();
>          }
>     }
> 
>     void purchase(Bike b) {
>          b.newOwner(this);
>          bike = b;
>     }
> }
> 
> void main() {
>     Bike[10] store;
>     store[] = new Bike(null, "street");
> 
>     Human joe = new Human("Joe");
>     joe.ride();
> 
>     // Joe buys a new bike
>     joe.purchase(store[4]);
> }
> 
> assuming I didn't mess up again, if you try to run it without the second 
> line in main you should get either a segfault as I don't recall D having 
> the nullPointerExceptions. Anyway, the second line is filling the array 
> of Bike with instances of Bike. You may want to try but I don't think it 
> will work.
> 
> Bike[10] store = new Bike(null, "street);
Runs fine with the bottom line in


More information about the Digitalmars-d-learn mailing list