Simple Example Program For Destructor In C++
On this page (9sections)
About this program
This is an example program in c constructor example programs. Read the concept first: Constructors and Destructors in C++ Classes, then study the code and output below.
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
Related Pages
Learn the concept first, then study the code:
- C++ Programs — Browse all C++ Programs.
- Constructors and Destructors in C++ Classes — Tutorial — constructors, destructors and overloading.
- Simple Example Program For Constructor In C++ — More in c constructor example programs.
- Simple Parameterized Constructor For Find Prime Number Example Program In C++ — More in c constructor example programs.