New Operator in C++:


The newoperator in C++ is used to allocate memory for a variable or an object at runtime. When the newoperator is used, the variables or objects are treated as pointers to the memory location allocated to them.

To allocate memory for a single element of a specified data type (which can be a built-in data type, structure, or class), the newoperator is used in the following manner:

// Request memory allocation for variable Variable_Name
Data_type* Variable_Name = new Data_type;

// Or

// Request memory allocation for variable Variable_Name and assign 10 to it
Data_type* Variable_Name = new Data_type(10);

To allocate memory for an array, the newoperator is used as follows:

Data_type* Variable_Name = new Data_type[Size_of_Array];

Here is a simple example demonstrating how to use the newoperator to allocate dynamic memory in C++:

NEW OPERATOR - C++ Copy to Clipboard  
#include <iostream>
using namespace std;

int main() {
    int* ptr; // Pointer to int
    int num;  // To store the total number of elements

    cout << "Enter the total number of elements to input: " << endl;
    cout << "Total Number: ";
    cin >> num;

    // Dynamic memory allocation for an array of size num
    ptr = new int[num];

    cout << "\nEnter your " << num << " elements:" << endl;
    for (int i = 0; i < num; i++) {
        cout << "Element #" << i + 1 << ": ";
        cin >> ptr[i];
    }

    cout << "\nYour entered elements are:" << endl;
    for (int i = 0; i < num; i++) {
        cout << ptr[i] << " | ";
    }

    // Releasing the allocated memory
    delete[] ptr;

    return 0;
}

To allocate dynamic memory using the newoperator, a pointer is required. This pointer will hold the address of the allocated memory. In the example above, we declare a pointer to intnamed ptrand allocate enough memory to store integers. If the requested memory exceeds the available heap space, an error may occur. Therefore, it is advisable to check for errors during memory allocation.

Here's an improved version of the above example with error checking:

NEW OPERATOR - C++ Copy to Clipboard  
#include <iostream>
using namespace std;

int main() {
    int* ptr; // Pointer to int
    int num;  // To store the total number of elements

    cout << "Enter the total number of elements to input: " << endl;
    cout << "Total Number: ";
    cin >> num;

    // Dynamic memory allocation for an array of size num
    ptr = new (nothrow) int[num];
    
    if (ptr != nullptr) { // Error checker
        cout << "\nEnter your " << num << " elements:" << endl;
        for (int i = 0; i < num; i++) {
            cout << "Element #" << i + 1 << ": ";
            cin >> ptr[i];
        }

        cout << "\nYour entered elements are:" << endl;
        for (int i = 0; i < num; i++) {
            cout << ptr[i] << " | ";
        }

        // Releasing the allocated memory
        delete[] ptr;
    } else { // If an error occurs while allocating memory
        cout << "An error occurred while allocating memory." << endl;
    }

    return 0;
}

In the improved example, the nothrowkeyword ensures that if memory allocation fails, nullptris returned instead of throwing an exception. The program checks if ptris nullptrand handles the error appropriately.

The deleteoperator is used to free the allocated memory when it is no longer needed. It is the programmer's responsibility to release the allocated memory. Here's how to use the deleteoperator:

// Allocate memory for a single element
Data_type* Variable_Name = new Data_type;
delete Variable_Name; // Release memory

// Allocate memory for an array
Data_type* Variable_Name = new Data_type[Size_of_Array];
delete[] Variable_Name; // Release memory

Here is another example that demonstrates dynamic memory allocation using the newoperator in a simple marks calculator program:

NEW & DELETE - C++ Copy to Clipboard  
#include <iostream>
#include <cstdlib> // exit() function
using namespace std;

int main() {
    cout << "\t\t\tMARKS CALCULATOR" << endl;
    int no, i, ans; // no = total number of subjects, i = loop counter

    // Pointer to store subject marks, sum to calculate total, percentage
    float *subject, sum = 0, percentage;

    cout << "\n\nEnter the total number of subjects: ";
    cin >> no;

    // Allocate memory for subjects using new operator
    subject = new (nothrow) float[no];
    if (subject != nullptr) { // Error checker
        cout << "\n\nEnter subjects marks:" << endl;
        for (i = 0; i < no; i++) { // Loop to get data
            cout << "Subject No " << (i + 1) << ": ";
            cin >> subject[i];
            sum += subject[i];
        }
        percentage = (sum / (100 * no)) * 100;

        // Display data
        cout << "\n\n\t\tPress 1 to Display:" << endl;
        cout << "\t\tPress 2 to Exit:" << endl;
        cout << "\nYour Ans: ";
        cin >> ans;
        cout << "\n\n";

        if (ans == 1) { // Answer checker
            cout << "\tSubject: \tMax:" << endl;
            cout << "\n";
            for (i = 0; i < no; i++) { // Loop to read and print data
                cout << "\tSubject No " << (i + 1) << "\t" << subject[i] << endl;
            }
            cout << "\t==================" << endl;
            cout << "\n\tThe Sum is: \t" << sum << endl;
            cout << "\n\tPercentage is: \t" << percentage << " %" << endl;
        } else {
            cout << "Thank you...!!" << endl;
            exit(0);
        }

        // Release the allocated memory
        delete[] subject;
    } else {
        cout << "Sorry...!! Memory not allocated." << endl;
        cout << "Check your code again." << endl;
        exit(0);
    }

    return 0;
}

In the example above, the program allocates memory dynamically to store subject marks, calculates the sum and percentage, and displays the results. The memory is released using the delete[]operator after it is no longer needed. If memory allocation fails, the program handles the error gracefully.