Simple Example Program For Destructor In C++

Destructor Overview

Definition

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

Destructor looks like a normal function and is called automatically when the program ends or an object is deleted.

Rules Of Destructor

  • Should start with a tilde(~) and same name of the class.
  • Destructors do not have parameters and return type.
  • Destructors are called automatically and cannot be called from a program manually.

Destructor Usage

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

Destructor Syntax

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

Simple Destructor Example Program For 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