Simple Example Program For Destructor In C++

Definition

The destructor is a special member function which is called automatically when the object goes out of scope.

Rules

  • Should start with a tilde(`) and same name of the class.
  • Destructors didn't have parameters and no return type.

Usage

  • Releasing memory of the objects.
  • Closing files and resources.

Syntax

Class class_name {
public:
 `class_name() //Destructor
   {
   }
}

Example Program

// Header Files
#include<iostream>
#include<conio.h>

//Standard Namespace Declaration

using namespace std;

class BaseClass // Class Name
{
public:
   //Constructor of the BaseClass
   BaseClass() {
      cout << "Constructor of the BaseClass : Object Created"<<endl;
   }
	
   //Destructor of the BaseClass
   ~BaseClass() {
      cout << "Destructor of the BaseClass : Object Destroyed"<<endl;
   }
};


int main ()
{
	// Object Declaration for BaseClass
	BaseClass des;
    
	// Wait For Output Screen
	getch();

	//Main Function return Statement
	return 0;
}

Sample Output

Constructor of the BaseClass : Object Created
Destructor of the BaseClass : Object Destroyed