A destructor is a special function member of a class that is automatically called when an object about to be deleted by delete operator. It always has the same name as the class preceded by a ‘tilt’ ~ symbol and has no return type. It is used to free allocated memory used by an object. It takes no arguments.
Example:
#include<string.h> #include<iostream.h> class student { private: char *name; public: student() { name = (char *)new char[20]; if(name) { strcpy(name, ""); } else { name = NULL; } } char* get_name() { return name; } void set_name(char *student_name) { if(name && student_name) { strcpy(name, student_name); } return; } }; int main(int argc, char* argv[]) { student * s_ptr; s_ptr = new student(); if(s_ptr) { s_ptr->set_name("ABC"); cout << "Student Name : " << s_ptr->get_name(); delete s_ptr; } else { cout << "Memory allocation error"; } return 0; }
About our authors: Team EQA
You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.