What is destructor?
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:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
How destructors are different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
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.
Can a destructor be virtual?
Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function. See virtual destructor for more details.
You may like to take a quiz on destructors.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Playing with Destructors in C++
- C++ Interview questions based on constructors/ Destructors.
- Represent N as sum of K even or K odd numbers with repetitions allowed
- Area of Circumcircle of an Equilateral Triangle using Median
- Find the day of the week after K days from the given day
- Check whether a given number N is a Nude Number or not
- Number formed after K times repeated addition of smallest divisor of N
- Count of numbers with all digits same in a given range
- Convert the number from Indian system to International system
- Sum of the products of same placed digits of two numbers
- Find the Nth Hogben Numbers
- Count of ordered triplets (R, G, B) in a given original string
- Product of all the pairs from the given array
- Construct an Array such that cube sum of all element is a perfect square