How to create a new object

Oct 21, 2008 at 2:09pm
I just learned about objects. But I still dont know how to create a new one within the program.
For example:

I am writing a Harvest Moon type farming sim. I have a writen the class for the crops. Now everytime the player plants a seed, I need the program to create a new instance of that class. After the player picks the crop, that object should be deleted on its own, is that correct?

I really hope I asked that question in a way that you could understand. If not sry, and I will try to make it clearer.
Oct 21, 2008 at 3:58pm
Hello! Use new/delete operators.
Declaration:
TypeOfObj *<name>=new TypeOfObject;
delete <name>;


U can also use "malloc" and "free", but this are from C.
TypeOfObj *<name>=(TypeOfObj *) malloc(sizeof(TypeOfObj));
free(<name>);


For new and delete....if u want to use an array, the declaration is:
TypeOfObj *<name>=new TypeOfObject [dimensions];
delete[ ] <name>;

Last edited on Oct 21, 2008 at 3:58pm
Oct 21, 2008 at 4:10pm
I would be wary of using malloc()/free() for creating and deleting objects. If your class has constructors/destructors they will not be called.

new/delete is the way to go.
Last edited on Oct 21, 2008 at 4:15pm
Oct 21, 2008 at 4:30pm
great, thank you smok006 and jlamothe.
Topic archived. No new replies allowed.