oop tutorials
Jesse Phillips
jessekphillips at gmail.com
Tue Mar 4 08:52:02 PST 2008
On Tue, 04 Mar 2008 16:56:15 +0100, Saaa wrote:
> Could anybody give a simple example of unallocated class reference use?
> I think that would explain it all to me :)
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