C++ Destructors

October 27, 2015 Posted by WithU Technologies
As like Constructors are called when new object is created, Destructors are also called when an object is to be deleted.
·         The Destructor is also initialised as like the constructor by the name of the class. The only difference between them is that Destructor used a tilde (~) prefix, which is not in the case for Constructor.

·         Destructor does not use any parameters, as it is only used to destroy an object.

·         Destructors can’t return a value.

·         They are used to save resources by closing by closing the files which will release the memory used by some out of scope objects.

·         Defining a destructor is not mandatory.

·         Destructors can’t be overloaded.

·         One Destructor is used for each class.

·         So in the header file of our class we will declare what the class will do.

#ifndef NEWCLASS_H_

#define NEWCLASS_H_

class NewClass {

public:

      NewClass();

      ~NewClass();

};

#endif /* NEWCLASS_H_ */

·         So we declared the destructor in the header file, now we can write the implementation in the source file i.e. NewClass.cpp in my case.

#include "NewClass.h"
#include <iostream>   // iostream header is included to use cout

using namespace std;   //namespace standard library is also included

NewClass::NewClass() {

      cout<<"Object is created and so the Constructor is called"<<endl;

}

NewClass::~NewClass() {

      cout<<"Object is destroyed and so the Destructor is called"<<endl;

}

·         In case of main function, we just need to create an object to complete this example.

·         Thus when the object is created, Constructor will be called and at the time of its deletion, Destructor will be called after the completion of program’s execution.

#include <iostream>
#include "NewClass.h"   // Include our classes to the main function

using namespace std;

int main()

{

      NewClass NewObject;  //New Object is created

}