NewOperator

'new' Operator
The new operator dynamically allocates memory on the heap rather than on the stack. After allocation it initializes it using the constructor. It is often used to declare pointers. Since the object is stored on the heap rather than the stack, the program needs to know when to delete it. This is different in some programming languages.

In Java
Since almost everything you declare in java is a pointer/reference, the new operator is used a lot when initializing objects. Java's garbage collector is responsible for deleting the data when it decides it is no long obtainable from the program.

code format="java" public class Main{ public class SomeClass{ public SomeClass{ x = y = 5; }       int x, y;    } public static void main(String[] args){ SomeClass myClass = new SomeClass; //used new operator that calls the constructor } } code

In C++
In C++ there is a function opposite the constructor, call the destructor that returns the memory allocated back to the heap. When working on the stack, the destructor is called automatically every time you leave a block{} of code. code format="cpp"
 * 1) include

struct book{ book{ //constructor printf("I see a book(Constructor).\n"); }   ~book{ //destructor printf("I close the book(Destructor).\n"); }   void read{ printf("I read the book."); } };

int main{ printf("I'm at the library.\n"); { //starting a new block here book a;   } //closed the block, all destructors for data in the block will be called

printf("Didn't like that book.\n"); {       book b;        b.read; }   printf("Leaving the library.\n");

return 0; } code code Output: I'm at the library. I see a book(Constructor). I close the book(Destructor). Didn't like that book. I see a book(Constructor). I read the book. I close the book(Destructor). Leaving the library. code

Any object created on the heap with the new operator won't be deleted if you end a block because the program doesn't know if your using it someplace else. The delete operator must be called when your program is 'done' with the object created with the new operator. If this is ignored your program will have memory leaks, because the memory will never be returned to the heap.

code format="cpp"
 * 1) include

struct person{ char *name; int ssn, age;

person(char *name, int age, int ssn){ //constructor this->name = name; this->age = age; this->ssn = ssn; }   ~person{ //destructor //the compiler can take care of deleting the ints for you but delete[] name; //the char is a pointer so you have to delete it manually } };

int main{ person *tyler; //a pointer to a person object tyler = new person("Tyler", 18, 55555); //create the object with new operator printf("%s's age is %d.\n", tyler->name, tyler->age);

delete tyler; //call the destructor

return 0; } code