The new operator replaces the malloc function provided in C to reserve storage taken from the heap.
The new operator requires one operand that describes the type of data to be stored in the memory. Here are some examples.
int *ptr1; // Declare a pointer to int.
ptr1 = new int; // Reserve storage and point to it.
float *ptr2 = new float; // Do it all in one statement.
delete ptr1; // Free the storage.
delete ptr2;
struct House // Declare a complex structure.
{
int Floors;
int Windows;
};
House *ptr3 = new House; // Reserve storage and point to it.
delete ptr3;
|
Blocks or arrays of storage can also be reserved as shown in the next example.
char *ptr
ptr = new char[80];
delete [] ptr; // Free the storage.
|
For built in datatypes (int, float etc) new and malloc can be intermixed in the same code. In practice, it is probably best to continue using malloc in existing code and new in fresh code. This is because you can not use delete with storage thats been reserved with malloc and visa versa. If you keep to one method or the other you are less likely to make a mistake.
If you are creating an object from a class, you will have to use new.
Here is a discussion on multi dimensional arrays from the C programming perspective. For a C++ perspective, read on.
Just as with C, you should check that new was sucessful. Click here for an explanation.
Example program.
delete keyword.
malloc function.
free function.
Multi dimensional arrays.
| Top | Master Index | C++ Keywords | Functions |