C++ Destructor
Destructor c++
What is a destructor?
Destructor name of destructor tells that something destroys, Exactly destructor destroy means delete (clean up)the memory in the c++ language.
On the other way, the destructor is contrary (opposite) to the constructor. The constructor is used to clearing the object and the destructor is used to remove the object.
Why need of destructor in c++?
Suppose we use heap memory or main memory and we allocate some memory but we do not free the memory for computers.Then there is memory wastage problem happened and problem in memory management. There is a need for something which clears the memory then destructor come into being. Destructor just frees the memory space.
How to use destructor?
The syntax of destructor in c++:
For example of destructor :
#include<iostream>
using namespace std;
class userarray{ //create the class
private:
int *ptr ;
int size ;
public:
userarray(int siz) //constructor
{
size= siz ;
ptr= new int[size];
cout<<" constructor "<< endl ;
}
~userarray() //destructor
{
delete []ptr ;
cout<<" destructor "<<endl;
}
};
int main()
{
userarray obj(5); //create object
return 0;
}
Similarities with the constructor:
Both have some sort of similarities.
Both have the same name as the class name.
Both have no return data type.
The difference with the constructor:
Constructors allocate the memory but the destructor deletes the memory.
The constructor may be parameterized but destructor does not parameterize.
Destructor has ~ sign the name but the constructor does have any sign.
Can the destructor be virtual?
Yes, the destructor be virtual. Infact, during the usage of virtual function make virtual destructors in the base class is a good idea.
What are the Advantages of destructor?
Destructor is very useful in memory management special memory leakage or memory loss.
We can use a destructor to avoid dangling pointers.
During the usage of the heap, memory destructor is very helpful.
Please write the comment,if you find anything incorrect and any problem in the above topic or you want to share more information about the above topic.
Comments
Post a Comment