Introduction
Destructor
Constructors serve to automatically initialized variables data members at the point of creation. Destructors are complimentary to constructors. They serve to de-initialized objects when they are destroyed.
A destructor may be called either when the object goes out of scope or when it is destroyed explicitly using the delete operator. A destructor, like a constructor has the same name as that of the class, but is prefixed by the tilde (‘~’) symbol. A class can’t have more than one destructor. And a destructor can’t take arguments or specify a return value consider the declaration of a word class as given below.
class word { private: char *str_word; public: word(char *s) { str_word=new char[strlen()+1]; strcpy(str_word, s); } int getlen() { return strlen(str_word); } Char *getword() { return str_word; } ~word() { delete str_word; } };
A destructor is normally not explicitly invoked though it can be done as follows:
word *word1;
word1->word::~word;
//example on constructors and destructors #include<iostream.h> class CRectangle { int *width, *height; public: CRectangle(int, int); ~CRectangle(); int area() { return(*width * *height); } }; CRectangle::CRectangle(int a, int b) { width= new int; height =new int; *width=a; *height =b; } CRectangle::~CRectangle() { delete width; delete height; } int main() { CRectangle rect(3, 4), rectb(5, 6); cout<<”rect area:”<<rect.area()<<end1; cout<<”rectb area:” }
Comments/Suggestions are invited. Happy coding......!
Comments Post a Comment