Hello friends, in this post today, we learn about what is Destructor in c++ and why we use Destructor in c++. so lets start...
Destructor in c++ |
Destructor:-
Destructor is a special and instance member function of a class.
Destructor is a member function whose name must be same as class name but is preceded by a tilde sign (~).
The purpose of destructor is to destroy the object when it is no longer needed or goes out of scope.
It should be defined to release resources allocated to an object.
Features of Destructor:-
Destructor should be declared in the public section.
Destructor can never be static.
Once a destructor is called for a object, the object will no longer be available for the future reference.
Destructor never takes any argument nor it returns any value nor it has return type (no overloading is possible).
Destructor is invoked automatically by the complier when object goes out scope of the program.
There is no explicit or implicit category for a destructor. They are always called implicitly by the compiler.
Destructor can be used for housekeeping work such as closing the file, de-allocating the dynamically allocated memory etc. Closing a file in destructor is a good idea as user might forget to close the file associated with object. But as the object goes out of scope destructor will be called and all code written in destructor executes which will always result in closing the file and no data loss may be there. When new is used for allocation of memory in the constructor we must always use delete in the destructor to be allocate the memory.
Example:
Output:
I hope that whatever information I have given in this post today, you have liked it and you have understood it.so keep learning and wait for the next post that will help you to increase your knowledge with the something new information.
Thank you so much for reading. And take care about yourself and your family.
Comments
Post a Comment