C++ Tutorial
Class and Object
Reference
Inheritance and Derivation
Polymorphism and Virtual Functions
Operator Overloading
Template
Exception
Object Oriented Advanced
Input/Output Stream
File Operations
In C++, a destructor is a special member function that gets executed automatically when an object goes out of scope or is explicitly deleted. Its main purpose is to release resources and perform cleanup tasks, such as deallocating memory, closing files, or releasing network connections.
In this tutorial, we'll cover how to define and use destructors in C++ classes.
~
. A destructor doesn't take any parameters or return a value, and there can only be one destructor per class. The destructor is automatically called by the compiler when the object is destroyed.Example:
#include <iostream> class MyClass { public: MyClass() { std::cout << "Constructor called." << std::endl; } ~MyClass() { std::cout << "Destructor called." << std::endl; } }; int main() { MyClass obj; return 0; }
Output:
Constructor called. Destructor called.
Example:
#include <iostream> class ResourceHolder { public: int* data; ResourceHolder(int size) { data = new int[size]; std::cout << "Resource allocated." << std::endl; } ~ResourceHolder() { delete[] data; std::cout << "Resource deallocated." << std::endl; } }; int main() { { ResourceHolder holder(10); } // holder goes out of scope here std::cout << "End of the main function." << std::endl; return 0; }
Output:
Resource allocated. Resource deallocated. End of the main function.
By using destructors in your C++ classes, you can ensure proper resource cleanup and prevent memory leaks. Remember to follow the guidelines for defining and using destructors to create more robust and maintainable code.
How to implement a destructor in C++:
class MyClass { public: // Destructor ~MyClass() { // Destructor body (cleanup code) } };
Destructor for dynamic memory in C++:
class DynamicMemoryObject { public: int* dynamicData; // Destructor for dynamic memory cleanup ~DynamicMemoryObject() { delete dynamicData; } };
Virtual destructors in C++:
class Base { public: // Virtual destructor virtual ~Base() { // Destructor body } }; class Derived : public Base { public: // Destructor (implicitly virtual due to the virtual destructor in the base class) ~Derived() { // Destructor body } };
Destructor for objects with pointers in C++:
class ObjectWithPointers { public: int* dynamicData; // Destructor for cleanup with pointers ~ObjectWithPointers() { delete dynamicData; } };