Join super friendly code & developer communities

A place for coders and developers to share, learn and grow together.

C++ | Introduction to Destructors

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.

P.S. If you have any questions, click here to join our community and feel free to ask any questions.

Share:
Super friendly <br/>code & developer communities

Super friendly
code & developer communities

A place for coders and developers to share, learn and grow together.