Simple Destructor Scope Measurement Example Program In C++

Definition

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

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 ()
{
	cout<<"Simple Destructor Scope Measurement Example Program \n\n";

	{
		// Object 1 Declaration for BaseClass
		cout<<"Object 1 : Creation In Braces\n\n";
		BaseClass des1;
		// Object 1 des1 : End of Scope 
	}
	
    cout<<"Object 2 : Creation in Main Part\n\n";
    BaseClass des2;
    
	// Wait For Output Screen
	getch();

	//Main Function return Statement
	return 0;
}

Sample Output

Simple Destructor Scope Measurement Example Program

Object 1 : Creation In Braces

Constructor of the BaseClass : Object Created
Destructor of the BaseClass : Object Destroyed
Object 2 : Creation in Main Part

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