Wednesday 22 February 2012

Can a destructor be explicit y called if an object is created using the new operator? | Constructor in C++

No, a destructor cannot be explicitly called if an object is created using the new operator. When you allocate the memory with the new operator, you are responsible for managing it yourself. To avoid cluttering up your program with memory that you are no longer using, you should delete it with the delete operator. The new operator returns a pointer to the newly allocated memory. Therefore, deleting the object is more prefe able than to call the destructor explicitly. For example, if you allocate the object via a typical new expression, such as:
Jerry* j = new ZJerryQ;
Then, the destructor Jerry: :~Jerry () will automatically get called on deleting it via:
delete j; //Automatically calls j->~3erry()
An explicit calling of the destructor would not release the memory that has been allocated for the Jerry object itself. The following are the two advantages of using the delete operator:
? It calls the destructor
? It deal locates the memory