Topics

6/recent/ticker-posts

Destructors In OOPS

Destructors In OOPS 


Definition: A destructor,as the name implies,it is used to destroy the objects that have been created by a constructor. This can be used to guarantee a proper clean up when an object goes out of scope

Like a constructor ,destructor is a member function whose name is same as the class name but is preceded by a tilde.

For example the destuctor for the class integer can be defined as shown below

Syntax:

    ~integer()
      {

       }
1. A destructor never take any  arguments nor does it return any value. 

2. It will be invoked implicitly by the compiler upon the exit from the program(or block or function as the case may be)to clean up storage that is no longer accessible.

3. It is a good practice to declare destructors  in a program since it releases memory space for future use.

4. Whenever new(Memory allocation operator) is used to allocate the memory in the constructors,we should use delete(memory release operator) to release that memory

Program to understand how destructors are used:

   #include<iostream.h>
  using namespace std;
   class test
    {
     int a,b;
    public:
    {
    test()
    {
    a=10;
    b=20;
    }
    ~test()
     {
   cout<<“a=“<<a<<endl;
   cout<<“b=“<<b<<endl;
}
};
int main()
{

  test t;
   }

Note: The programs are pre compiled and pre runned and if the user want to run the program again then they can use the button given after each and every program.

Post a Comment

0 Comments