How to delete array of objects in C++? Proof by C++ code for proper deletion

(Last Updated On: April 30, 2017)

Answer includes how to delete array of objects in C++ created dynamically with C++ code example with proof. In other words, delete array of pointers to objects in c++.

Interview Question: Write C++ code to create an array of objects using new keyword and delete these objects. Also, proof that all the objects are deleted properly.

Answer:

We know that when we create an object of a class dynamically from heap memory using new keyword, then we must delete it explicitly to avoid memory leaks in C++ programs after we are done with its operations.

Let’s take below class Pen as an example.

 

 

Below is an example, how we create an object of the class Pen dynamically and delete it after we are done with operations.

 

 

How to create array of objects of a class in C?

Let’s see how we create an array of objects in below C++ program example. In this example, we will create array of 3 objects, perform operation and delete dynamic array of pointers properly.

 

 

Output:

Constructor…
Constructor…
Constructor…
Writing…!
Writing…!
Writing…!
Destructor…!
Destructor…!
Destructor…!

Proof of proper deletion of array of objects in C++

First, note that if we create an object of a class and delete the object then class constructor and destructor will be called respectively.

In above example, we have created an array of 3 objects and delete it using statement delete [] pen; if we look at the output the class constructor and destructor were called 3 times each. means, we have deleted objects properly.

Now, If we delete the object using the statement “delete pen” ( This is general mistake a programmer make) then the destructor will be called only once and for rest 2 objects destructor will not be called and program will crash. and this will proof that objects are not deleted properly.

Lets see the output if we use statement “delete pen”

 

 

Output:

Constructor…
Constructor…
Constructor…
Writing…!
Writing…!
Writing…!
Destructor…!

and then program will crash at run time.

Conclusion:

In C++, single object of a class created dynamically is deleted using statement “delete pointer” and array of objects are deleted using statement “delete [ ] pointer”.