oop tutorials
Ty Tower
tytower at hotmail.com.au
Thu Mar 6 16:25:43 PST 2008
Jarrett Billingsley Wrote:
> "Jesse Phillips" <jessekphillips at gmail.com> wrote in message
> news:fqkejg$1vkn$1 at digitalmars.com...
> > 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.
>
> Nope. new Bike[10] allocates a new dynamically-sized array of length 10;
> the type of that expression is Bike[], not Bike[10]. It's really sugar for
> new Bike[](10). Thus its length can change.
>
> It's not actually possible to allocate a statically-sized array on the heap
> directly. You have to use a templated struct and allocate that.
>
>
I notice good old Jesse doesn't answer when someone corrects him. No thanks either
There is a definate problem
So Tango version
module Bike;
import tango.io.Stdout;
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) {
Stdout(name,"is now riding his new bike").newline;
}
else {
Stdout("This guy has to walk at first").newline;}
}
void purchase(Bike b) {
b.newOwner(this);
bike=b;
}
}
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]);
joe.ride();
}
/* 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.
*/
Interesting -thanks to all three of you
More information about the Digitalmars-d-learn
mailing list