Destructors in C++ - Part I

Not a pretty word? At least for us, the people of fairer sex. But you see, just like you need to throw away the junk from your house frequently, the unwanted objects need to be destructed. In order to avoid memory leakage. See we don't have fancy garbage collecting in C++.


Destructors are functions which are called when an object is destroyed. They deallocate memory. They also do other clean up stuff.

n is trivial.
 
class A  
 { 
private:
  int num; 
public:
  A(int n): num(n){} 
  ~A(){} 
 } ;


Our class has a constructor which initializes num to n. And it has a destructor which does nothing.

If a class does not define a destructor, then compiler creates an implicit destructor which is trivial. 


Destructor functions have same name as Class, prefixed by ~ (tilde) operator. They do not have a return type. If your class has no dynamically allocated members and has no members with explicit destructors and has no base class destructors, then destructor functio
Let us keep in mind that for any class, the compiler provides the following functions

  1. Default constructor
  2. Copy constructor
  3. Destructor
  4. Assignment operator

Destructor call:

Note that similar to constructor, a destructor is never called explicitly.
  1. For local objects, a destructor is called when the objects goes out of scope. 
  2. For static or external objects, the destructor is called when the program is terminating.
  3.  For objects dynamically created using new operator, destructor is explicitly called when delete operator is used.
To undestand this concept, compile and run this program.

 

#include <iostream>
using namespace std;
class A
{
private:
    int num;
public:
    A(int a):num(a)
    { 
        cout<<"Constructor of object"<<num<<"\n";
     }
    ~A()    
     {
        cout<<"destructor of object"<<num<<"\n";
     }
};
A glob_obj(100);
int main()
{
    A obj1(5);
    cout<<"Hello from main";
    A obj2(12);
    cout<<"end of main";
}

The destructor of objects is called in reverse order in which they are created. The class destructor is called first, then the destructors of members are called, then destructor of base class is called. 

You do not need a destructor just to show some messages on the console. You do not  a destructor, when you have allocated any members dynamically. This dynamic allocation will be done with new operator in the constructor. And releasing the memory should be done with delete operator in the destructor.


#include <iostream>
using namespace std;
class A
{
private:
    int num;
    int *ptr;
public:
    A(int a):num(a)
    { 
       ptr = new int;//allocation of memory to ptr
       cout<<"Constructor of object"<<num<<"\n";
     }
    ~A()    
     {
        delete ptr;//deallocation of memory
        cout<<"destructor of object"<<num<<"\n";
     }
};






Comments

Popular Posts