A Program of 'Destructor' :-


#include<iostream.h>
#include<conio.h>

class student
{
private:
int id;
float marks;
public:
student(int a,float b)
{
id=a;
marks=b;
}
void showdetails()
{
cout<<endl<<id<<"__"<<marks;
}
~student()
{
cout<<"Destructor is envoked";
}
};
void main()
{
student s1(5,50.5);
s1.showdetails();
getch();
}

Output:


Destructor is envoked
5__50.5

			


When does the destructor get called?

A destructor is automatically called when:
1. The program finished execution.
2. When a scope (the { } parenthesis) containing local variable ends.
3. When you call the delete operator.

Destructor rules :-

1. Name should begin with tilde sign(~) and must match class name.
2. There cannot be more than one destructor in a class.
3. Unlike constructors that can have parameters, destructors do not allow any parameter.
4. They do not have any return type, just like constructors.
5. When you do not specify any destructor in a class, compiler generates a default destructor and inserts it into your code.
Previous Next