Home »
C+ programs »
C++ constructor, destructor programs
C++ program to demonstrate example of destructors
Learn about the destructors in C++, how to implement destructors in C++ program?
[Last updated : March 02, 2023]
In this program we will learn to create Destructors in c++ programming language.
Destructors Program in C++
// C++ program to demonstrate example of destructors
#include <iostream>
using namespace std;
//Class Declaration
class Demo {
private: //Private Data member section
int X, Y;
public: //Public Member function section
//Default or no argument constructor.
Demo()
{
X = 0;
Y = 0;
cout << endl
<< "Constructor Called";
}
//Destructor called when object is destroyed
~Demo()
{
cout << endl
<< "Destructor Called" << endl;
}
//To take user input from console
void getValues()
{
cout << endl
<< "Enter Value of X : ";
cin >> X;
cout << "Enter Value of Y : ";
cin >> Y;
}
//To print output on console
void putValues()
{
cout << endl
<< "Value of X : " << X;
cout << endl
<< "Value of Y : " << Y << endl;
}
};
//main function : entry point of program
int main()
{
Demo d1;
d1.getValues();
cout << endl
<< "D1 Value Are : ";
d1.putValues();
Demo d2;
d2.getValues();
cout << endl
<< "D2 Value Are : ";
d2.putValues();
//cout << endl ;
return 0;
}
Output
Constructor Called
Enter Value of X : 10
Enter Value of Y : 20
D1 Value Are :
Value of X : 10
Value of Y : 20
Constructor Called
Enter Value of X : 30
Enter Value of Y : 40
D2 Value Are :
Value of X : 30
Value of Y : 40
Destructor Called
Destructor Called