Simple Example Program For Destructor In C++

Destructor Overview


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 {
 ~class_name() //Destructor

Simple Destructor Example Program For Program

// Header Files

//Standard Namespace Declaration

using namespace std;

class BaseClass // Class Name
   //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

	//Main Function return Statement
	return 0;

Sample Output

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