What is destructor
1 minute read
What is destructor? Explain.
Ø A destructor, as the name implies, is used to destroy the objects that have been created by a constructor.
Ø The destructor is a member function whose name is the same as the class name but is preceded by a tilde (~) sign.
Ø Syntax:
~ class-name() { . . . . //destructor body}
Ø For example: the destructor for the class student can be defined as shown below;
~ student () { . . . }
Ø It is called for the object that is going out of scope.
Ø A destructor never takes any arguments nor does it return any value.
Ø Destructor can be overloaded.
Ø It will be invoked implicitly by the compile at the exit time o program to clean up the storage that is no longer accessible.
Ø delete is used to free the memory.
Ø For example:
class A
{
int *X;
public:
A()
{
X = new int;
cout << “\n Constructor”;
}
~ A()
{
delete X;
cout << “\n Destructor”;
}
};
int main()
{
A a1,a2;
{
A a3;
}
{
A a4;
}
return 0;
}
Ø Output of the above program:
Constructor
Constructor
Constructor
Destructor
Constructor
Destructor
Destructor
Destructor
10) Explain the characteristics of a destructor.
Ø A destructor is invoked automatically by the compiler when its corresponding constructor goes out of scope and release the memory that is no longer required by the program.
Ø A destructor will not return any value and does not accept arguments and therefore it cannot be overloaded.
Ø A destructor cannot be declared as static, const or volatile.
Ø A destructor should be declared in public section.
Ø It is necessary that a destructor use a delete expression to deallocate the memory if constructor in the program uses the new expression for allocating the memory.
Ø A destructor is called in the reverse order of its constructor invocation.