Destructor function in C++

Destructor function is used to destroy class objects exists in program. Name of destructor is same as the name of constructor but tilde (~) symbol is used before it. The major purpose of destructor is to delete class objects when associated scope/block ends and add this free memory bytes to free memory pool (heap).So, that it will be available for other programs. It neither take any input nor return any output. Destructor function is automatically called by compiler when program control is shifted outside from current block.
डिस्ट्रक्टर फंक्शन का प्रयोग प्रोग्राम में उपस्थित क्लास ऑब्जेक्ट्स को नष्ट करने के लिए किया जाता है।डिस्ट्रक्टर का नाम कंस्ट्रक्टर के नाम के सामान ही होता है परन्तु इसके पूर्व टिल्ड (~) चिन्ह का प्रयोग किया जाता है। डिस्ट्रक्टर का मुख्य उद्देश्य, स्कोप / ब्लॉक के समाप्त हो जाने पर सम्बंधित क्लास ऑब्जेक्ट्स को नष्ट करना एवं इन फ्री मेमोरी बाइटस को फ्री मेमोरी पूल (हीप) में जोड़ना है। जिससे इनका प्रयोग अन्य प्रोग्राम में किया जा सके। यह ना तो कोई इनपुट ग्रहण करता है ना ही कोई आउटपुट प्रदान करता है। जब प्रोग्राम कंट्रोल ब्लॉक के बाहर पहुँचता है तब कम्पाइलर द्वारा डिस्ट्रक्टर फंक्शन को स्वतः कॉल किया जाता है। 
Syntax:-
public : ~class_name ( ){
statement(s);
...............
...............
}

Example:-

C++ program for Destructor function
#include<iostream.h>
#include<conio.h>
int count=0;
class addition{
float a,b,c;
public:
addition();
~addition();
};
addition::addition(){
count++;
cout<<"Number of Objects Created= "<<count<<endl;
a=b=c=0;
}
addition::~addition(){
cout<<"Number of Objects Deleted= "<<count<<endl;
count--;
}
void main(){
addition m,n,o,p;
{
cout<<"Block 1"<<endl;
addition x,y;
}
getch();
{
cout<<"Block 2"<<endl;
addition w,z,v,u;
}
getch();
}

No comments:

Post a Comment