Archived

This topic is now archived and is closed to further replies.

Punx409

Where to use new/delete?

Recommended Posts

Punx409    122
I know this is probably a simple thing that I''m overlooking but I''m just starting out (far as Tetris) and I haven''t seen a use for new/delete so far and have heard a bunch of negative stuff like memory leaks and the like from using them. Can someone explain to me where in game programming using new/delete would be appropriate?

Share this post


Link to post
Share on other sites
neurokaotix    100
Use new when creating a pointer to a class, e.g. CEngine * XEngine = new CEngine();. Use delete when you want to destroy a pointer, e.g. delete XEngine;. Hope that explains it (and I hope I got the terminology correct lol)

Edit: Had to fix something

[edited by - neurokaotix on January 30, 2003 3:19:54 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Heres a little code for you

class myClass
{
public: // this is for simplisities sake
myClass(){int = 0;};
int value;
};

void main()
{
myClass *myPointer; // creates a pointer of the type myClass, but it doesnt point to anything YET

myPointer = new myClass; // this creates an instance of the type my pointer in what some call the heap(memory) and fills my pointer with the address of that instance this is call a DYNAMIC VARIABLE

(*myPointer).value = 10; //This sets the .value member to 10, NOTE the *myPointer is in brackets this is because of the rules of preccedance you must dereferance the pointer BEFORE you can access its members

myPointer->value = 20; // This works too because the arrow -> operator handle the preceedance for you

//finaly,

delete myPointer; This deletes the instace of myClass from the heap free that memory. If you dont do this and point your pointer at something else your access to the original instance of myClass this is called a lost pointer and creates a memory leak



Where all of this leads to is Dynamic Arrays and Linked Lists.

Share this post


Link to post
Share on other sites