C++ - New Operator

The new operator in C++ is used to dynamically allocate memory for objects at runtime. It is used to create objects on the heap instead of the stack. The new operator returns a pointer to the dynamically allocated memory, which can be assigned to a pointer variable.

type *pointer = new type;

In this syntax:

type represents the data type of the object you want to allocate.

pointer is a pointer variable that will store the address of the dynamically allocated memory.

int* number = new int;  // Dynamically allocate memory for an integer
if (number != nullptr) {
    *number = 10;  // Assign a value to the dynamically allocated memory
    cout << "Value: " << *number << endl;  // Output: 10
    delete number;  // Deallocate the dynamically allocated memory
    number = nullptr;
}

In this example, the new operator is used to allocate memory for an integer. The number pointer is assigned the address of the dynamically allocated memory. The value of 10 is then assigned to the memory using the dereference operator (*). Finally, the delete operator is used to deallocate the memory, freeing it up for reuse.

It's important to note that every call to new must be followed by a corresponding call to delete to prevent memory leaks. Failing to deallocate dynamically allocated memory can lead to memory exhaustion and inefficient memory usage.

You can also use the new operator to allocate memory for arrays:

type *pointer = new type[size];

In this syntax, size represents the number of elements in the array. The new operator allocates contiguous memory for the array elements.

int size = 5;
int* numbers = new int[size];  // Dynamically allocate memory for an integer array
if (numbers != nullptr) {
    for (int i = 0; i < size; i++) {
        numbers[i] = i + 1;  // Assign values to the array elements
    }
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";  // Output: 1 2 3 4 5
    }
    cout << endl;
    delete[] numbers;  // Deallocate the dynamically allocated memory
    numbers = nullptr;
}

In this example, the new operator is used to allocate memory for an integer array of size 5. The array elements are assigned values using a loop. Finally, the delete[] operator is used to deallocate the memory for the array.

Remember to use delete[] when deallocating memory for arrays to ensure that all elements are properly deallocated.