Delete operator is used to release dynamically allocated memory in CPP

Q.  Which of the following operator is used to release the dynamically allocated memory in CPP?
- Published on 17 Jul 15

a. remove
b. free
c. delete
d. both b and c

ANSWER: delete
 

    Discussion

  • Ramesh   -Posted on 23 Oct 15
    delete operator is used to release the dynamically allocated memory in CPP. The new operator allocates memory dynamically, it should be released otherwise resource will be captured unnecessary.
    Example.
    class MyClass {
    private:
    int n;
    float *ptr;
    public:

    MyClass() {
    cout << "Enter total number of students: ";
    cin >> n;

    ptr = new float[n];

    cout << "Enter marks of students." << endl;
    for (int i = 0; i cout << "Student" << i+1 << ": ";
    cin >> *(ptr + i);
    }
    }

    ~MyClass() {
    delete[ ] ptr;
    }

    void Show() {
    cout << "\nDisplaying Marks of students." << endl;
    for (int i = 0; i cout << "Student" << i+1 << " :" << *(ptr + i) << endl;
    }
    }

    };
    int main() {
    MyClass obj;
    obj.Show();
    return 0;
    }
    When the object goes out of scope then, destructor is automatically called.

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)