| || |
Join Date: Aug 2008
Using new and delete Operators in C++
C++ offers programmers a means to create variables dynamically using new operator. The new operator determines the type of receiving pointer and converts its return value appropriately. Memory is allocated. To release the memory allocated,C++ uses delete operator.
The new operator, when used with the pointer to a data type, allocates memory for the item and assigns the address of that memory to the pointer. The delete operator does the reverse, it de-allocates the memory allocated to the variable. The C++ new operator is used to allocate memory from the heap. The advantage of the new operator is that it offers safety in terms of type and size. Whereas malloc only takes one argument, the desired size in bytes. The argument to the new operator identifies the type of the variable to create, which ensures that the user is getting memory of the intended size and type. When no longer needed, memory that is allocated with new should be deallocated with delete.
char *name; //Declare a pointer
name = new char; //Allocates 31 bytes memory for the object
cout<< "Enter name : " << endl; //Will be displayed on the screen
cin >> name;
cout << name <<;
delete  name; //Destroys the object by de-allocating the memory