Destructors in C++
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
class String { private: char *s; int size; public: String(char *); // constructor ~String(); // destructor }; String::String(char *c) { size = strlen(c); s = new char[size+1]; strcpy(s,c); } String::~String() { delete []s; } |
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.
Related Articles :
Constructors in C++
Virtual Destructor
Pure virtual destructor in C++
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Playing with Destructors in C++
- C++ Interview questions based on constructors/ Destructors.
- Print the Alphabets A to Z in Star Pattern
- How can we write main as a class in C++?
- Types of Errors in Java with Examples
- Minimum distance from a point to the line segment using Vectors
- Array formed from difference of each element from the largest element in the given array
- Empty an Array by removing maximum of K value from it
- Program to find the Product of diagonal elements of a matrix
- The "Hello World" To Programming
- Difference between Virtual function and Pure virtual function in C++
- cin get() in C++ with Examples
- Difference between Increment and Decrement Operators
- Program to calculate Percentile of Students

