In object-oriented programming, a destructor (sometimes shortened to dtor) is a method which is automatically invoked when the object is destroyed. Its main purpose is to clean up and to free the resources which were acquired by the object along its life cycle and unlink it from other objects or resources invalidating any references in the process. The use of destructors is key to the concept of RAII.
In a language with an automatic garbage collection mechanism, it is impossible to deterministically ensure the invocation of a destructor, and hence these languages are unsuitable for RAII. In such languages, unlinking an object from existing resources should be done by an explicit call of appropriate function (usually called Dispose). This method is also recommended for freeing resources rather than using Finalizers for that.
Virtual destructor
A virtual destructor is a destructor that can be overridden by subclasses. In C++, use of virtual destructors in inheritance hierarchies facilitates proper clean-up of objects, preventing resource leaks and heap corruption.
C++
In C++, the destructor function is the same name as the class, but with a tilde (~) in front of it. If the object was created locally, its destructor is automatically called, and if the object was created with the new keyword, then its destructor is called when the pointer that points to the object is delete'd. This particular class holds a_pointer to a list of character strings. A destructor is required when dynamically created data elements were used, files were opened, locks have to be unlocked or a copy constructor was used.
#include
using namespace std;
class myclass {
public:
string* [] a_pointer;
void newstring(void)
{
a_pointer[current++] = new string();
}
~myclass() // THIS IS THE DESTRUCTOR METHOD
{
int n = 0;
while (n <= current)
delete a_pointer[n++];
}
private:
int current;
};
For the orher programming language visit http://en.wikipedia.org/wiki/Destructor_(computer_science)
0 comments:
Post a Comment