adspace
What is the need of a destructor? Explain with the help of an example.
Answer Posted / Sangh Priya Rahul
A destructor is needed to clean up any resources (like memory, files, network connections etc.) that an object acquired during its lifetime. An example would be deleting dynamically allocated memory in C++ when an object is destroyed or goes out of scope. For instance, consider a class `MyClass` with a pointer member `data`. The destructor can be used to free this memory:
```cpp
MyClass::~MyClass() {
delete[] data;
}
```
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers