C++ | Introduction to Destructors

Join Programming and Development Chat Groups on Uphub.io

Introduction

This is a tutorial for destructors in c++. The program just constructs a object using constructor and destroys the object using destructor. The program is extendable. Go enjoy the program. Lets begin….

Program for using destructors in c++.

#include<iostream.h>
#include<conio.h>
//declare class
class test
{
 //public
 public:
 //constructor
 test()
 {
 cout<<"Object is Created"<<endl;
 }
 //destructor
 ~test()
 {
 cout<<"Object is destroyed"<<endl;
 }
 //function
 void live()
 {
 cout<<"Object is live"<<endl;
 }
};
 
//void main
void main()
{
//clear the screen.
clrscr();
//a block
{
//declare object
test obj;
//call functions
obj.live();
}
//get character
getch();
}

Output

Object is Created.
Object is live.
Object is Destroyed.

How does it work.

No need for input the program directly creates a object using constructor and destroys the object using destructor.

Extending it.

The program is extendable. This is a basic concept of c++, so can be implemented in any program that uses classes and objects.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Declare class.
  3. Declare constructor, destructor and functions.
  4. Add void main.
  5. Start program by first clearing the screen.
  6. Add a block.
  7. Declare object.
  8. Call the function.
  9. Get character.

At the end

You learnt creating the C++ program for using Destructors. So now enjoy the program.

Please  share it.

Sharing options: