What is the use of delete operator in c++?

Showing Answers 1 - 18 of 18 Answers

ryan

  • Sep 5th, 2011
 

To free some memory allocation, usually used with pointers.

  Was this answer useful?  Yes

Delete = free + destructor

So, If u want to free dynamically allocated memory, u can simply use free.
But if u want to call destructor as well u will have to use delete.

Lets take an example :

Code
  1. Case 1: A String

  2.  

  3. char * lstrString = (char *) malloc (6 * sizeof(char));

  4. strcpy(lstrString, "mehul");

  5.  

  6. In this case, I have allocated 6 Bytes on heap for lstrString.

  7. Now, to free this memory, I can use

  8.  

  9. free(lstrString);

  10. lstrString = NULL;

  11.  

  12. Case 2: A class

  13.  

  14. class A

  15. {

  16. public:

  17.            char * lstrString;

  18.  

  19.            A(char * pstrString)

  20.            {

  21.                    lstrString = (char *) malloc (strlen((pstrString)+1)  *  sizeof(char));

  22.                    strcpy(lstrString,  pstrString);

  23.            }

  24.  

  25.           ~A()

  26.           {

  27.                  free(lstrString);

  28.                  lstrString = NULL;

  29.           }

  30. }

  31.  

  32. int main()

  33. {

  34.         A obj("mehul");

  35.  

  36.         delete (obj);

  37. }




Now, In this case, i want to call destructor of A to free the memory.
So, I will have to use delete.

Amit

  • Jan 6th, 2012
 

Delete: is used to deallocate memory from the heap that is created by new.

When you call delete, it firstly call the destructor of that object and then deallocate memory from heap.

class A
{

};

int
main()
{
A *a = new A();
delete a;

A *arr = new A[10];
delete []arr;
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions