In a class use the new operator to crate a object of the class . Their constructor is used to allocat memory for the data member and fucntion , and distructor is use to free the memory . If we use delete inplace of distructor , will it work ???

Recommended Answers

All 4 Replies

destructor is called for once the program ends and memory is de-allocated for a class.i guess there also exists a default destructor(though i'm not sure). However using delete explicitly causes no harm.

Thanks , Here is again one question , if i delete the memory using the delete operator , than again destructor will try to free the same memory location .. it will create a problem , i guss .

In a class use the new operator to crate a object of the class . Their constructor is used to allocat memory for the data member and fucntion , and distructor is use to free the memory . If we use delete inplace of distructor , will it work ???

The program needs to delete the memory that was previously allocated. Default destructors do not do that, so you need to write your own destructor and delete the memory there. Yes you can delete memory in other parts of the program, but if you do that then set the pointer to NULL so that the delete in the destructor works correctly.

Little addition to AD's post.
Destructor is a member function or method of class which is called automatically when an object loose it's reference. Destructor is used to implement object specific cleanup code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.