Destructor
What is a destructor?
Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.
The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory.
- Destructor function is automatically invoked when the objects are destroyed.
- It cannot be declared static or const.
- The destructor does not have arguments.
- It has no return type not even void.
- An object of a class with a Destructor cannot become a member of the union.
- A destructor should be declared in the public section of the class.
- The programmer cannot access the address of destructor.
class String {
private:
char* s;
int size;
public:
String(char*); // constructor
~String(); // destructor
};
String::String(char* c)
{
size = strlen(c);
s = new char[size + 1];
strcpy(s, c);
}
String::~String() { delete[] s; }