C++ Destructor - Learn C++ , C++ Tutorial , C++ programming
Learn c++ - c++ tutorial - c++ destructor - c++ examples - c++ programs
What is destructor in C++?
- Destructor is a member function which destructs or deletes an object.
When is destructor called?
A destructor function is called automatically when the object goes out of scope:
- the function ends
- the program ends
- a block containing local variables ends
- a delete operator is called
The Class Destructor
- A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
- A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.
- Following example explains the concept of destructor:
When the above code is compiled and executed, it produces the following result:
Can there be more than one destructor in a class?
No, there can only one destructor in a class with classname preceded by ~, no parameters and no return type.
When do we need to write a user-defined destructor?
If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak.