1.Assume we've instantiated a static object named xyz of some class. When will xyz go out of scope?
2.Assume we've instantiated a dynamic object of some class. We used a pointer variable named p. Code a statement to free the memory occupied by abc.
1. Destructors destroy the object whenever the object goes out of scope. It has the same name as that of the class with a tilde (~) sign before it.
class xyz
{
~xyz();
};
Here, ~xyz() is the destructor of class xyz. Destructors don't take any argument and have no return type.
A destructor gets automatically called when the object goes out of scope. We know that a non-parameterized constructor gets automatically called when an object of the class is created. Exactly opposite to it, a destructor gets called when the object goes out of scope and destroys the object.
Note that the destructor will get automatically called even if we do not explicitly define it in the class.
2. Clean up memory with operator 'delete'. Apply to the pointer. Use 'delete [ ]' form for arrays:
delete ptr; // deallocates the integer allocated above
delete [ ] nums; // deallocates the double array
Get Answers For Free
Most questions answered within 1 hours.