NEW operator.


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 show in the next example.


    char *ptr
    ptr = new char[80];
    
    delete [] ptr;          // Free the storage.

Although new and malloc can be intermixed in the same code, it is probably best to continue using malloc in existing code and new in new 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.


Examples:

Example program.

See Also:

delete keyword.

C References

malloc function.

free function.


Top Master Index C++ Keywords Functions


Martin Leslie 17-Feb-96