• In C++ destructor is a member function of a class used to free the space occupied by or delete an object of the class that goes out of scope.
  • In class destructor has the same name as the name of the constructor function, but the destructor uses a tilde (~)sign before its function name.
  • It is used to free up the memory space allocated by derived class object or instance while deleting instances of the derived class using a base class pointer object.
  • A derived class or base class destructor use the virtual keyword that ensures both classes destructor will be called at run time.
  • First it calls the derived class and then base class to release the space occupied by both destructors.
  • If an object in the class goes out of scope or the execution of the main() function is about to end, automatically a destructor is called into the program to free up the space occupied by the class’s destructor function.
  • If a pointer object of the base class is deleted that points to the derived class, only the parent class destructor is called due to the early bind by the compiler.
  • In main function if the compiler compiles the code, it calls a pointer object that refers to the base class.
  • It executes the base class’s constructor() function and then moves to the derived class’s constructor() function and deletes the pointer object occupied by the base class’s destructor and the derived class’s destructor.
  • In program base class pointer only removes the base class’s destructor without calling the derived class’s destructor

Sample Code

using namespace std;  
class Base
{
public:
Base() // Constructor member function.
{
cout << "\n Constructor Base class"; // It prints first.
}
virtual ~Base() // Define the virtual destructor function to call the Destructor Derived function.
{
cout << "\n Destructor Base class"; /
}
};
// Inheritance concept
class Derived: public Base
{
public:
Derived() // Constructor function.
{
cout << "\n Constructor Derived class" ; /* After print the Constructor Base, now it will prints. */
}
~Derived() // Destructor function
{
cout << "\n Destructor Derived class"; /* The virtual Base Class? Destructor calls it before calling the Base Class Destructor. */
}
};
int main()
{
Base *bptr = new Derived; // A pointer object reference the Base class.
delete bptr; // Delete the pointer object.
}

Output

 

Categorized in: