Understanding delete operator in C++ With Examples

Hello, folks! In this article, we will be understanding the necessity and usage of the delete operator in C++.


Getting started with C++ delete() function

C++ language, being an object-oriented language, has the capability to create objects and manipulate the data variables at run-time. That is, they create and deletion of objects can happen dynamically and with ease.

The delete operator in C++ serves the purpose of deletion of arrays, objects, pointers, etc. The new operator assigns dynamic memory to the object or data variable. In order to delete the memory assigned, we use delete operator.

Syntax:

The delete operator deletes and thus deallocates the assigned memory from the heap structure.

Now that we have understood the working and need of delete operator, let us now understand the applications of delete operator in actual programming scenarios.


Variant 1: Deleting a void pointer using delete operator

The delete operator can be used to free the memory space occupied by the void pointer variable efficiently.

Example:

Output:


Variant 2: Deleting dynamically allocated memory through delete() function

The delete operator can be used to delete the memory that has been dynamically allocated by using the malloc() function to the pointer variable.

Example:

Output:


Variant 3: Deleting pointers with delete() function

During the delete operation on pointers, the pointer to the object or the variable does not get deleted. So, the delete operator deletes the memory space that the pointer points in the RAM.

Example 1: Deleting NULL pointers with delete operator

In the above example, we have destroyed the memory occupied by the NULL pointer variable.

Output:

Example 2: Deleting a pointer variable point to a particular value

In the above snippet of code, we have used delete operator to deallocate the memory space occupied by the pointer variable holding a data value. Here, the data value is cleared from the space occupied by the pointer variable.

Output:


Variant 4: Deleting an array object by delete() function

Array objects in C++ can be deleted using the delele[] operator effectively.

Example:

Output:


Summary

  • The delete operators deallocates the memory space occupied by the data variables, arrays or pointers.
  • Moreover, it does not destroy the pointer, rather the memory space used by the pointer gets deleted.
  • The delete[] operator deletes the space occupied by the array objects.

Conclusion

Thus, in this article, we have studied and understood the the working of delete operator in C++.


References

By admin

Leave a Reply

%d bloggers like this: