Class Destructor


Class Destructor as it's name suggests is a function which deletes an object.


A destructor function is called when
(1) Function ends
(2) Program ends
(3) Block consisting of local variables ends
(4) Delete operator is called


Destructors have same name as the class only with a tilde (~)

Destructors do not allow parameters and only one destructor in a class.




#include <iostream>
#include <string.h>

class string
   char *s;
   int size;
   string(char *); //constructor
   ~string(); //destructor

string::string(char *c)
  size = strlen(c);
  s = new char[size+1];
  std::cout<<"constructor called\n";

string::~string( )
  std::cout<<"desctructor called";
  delete [ ]s;

int main()
    string str("name");