Destructor In C++





Destructor in c++

It is used o destroy the object that has been created by a constructor. It is a member function whose name is the same as the class name but is preceded by tilde (~) symbol. A class can’t have more than one destructor. It takes no arguments and no return types can be specified for it (not even void). It is called automatically by the compiler when an object is destroyed.
The general syntax of the constructor and destructor is:-

Class Class_name
{
Private:
Public:
Class_name (); // constructor
~Class_name ();    //destructor
};

Need of destructor
Constructor allocates memory to the object. This allocated memory must be deallocated before the object is destroyed. This job of memory deallocation from object is done by special member function of the class. This member function I destructor. Hence, the most common use of destructor is to de-allocate and release memory that was allocated for the object by the constructor.

A  program to generate a series of Fibonacci number using the constructor.

#include<iostream.h>
#include<conio.h>
Class Fibonacci
{
Private:
Long int a, b, c;
Public:
Fibonacci ()
{
a=0;
b=1;
c=0;
}
Void display ()
{
Cout<<”\n\t”<<c;
c=a+b;
c=a;
a=c;
}
};
Void main ()
{
Fibonacci obj;
For (int i=o; i<=15;i++)
{
Obj.dispay ();
}
getch ();
}



Related posts:

  1. Constructor in C++ Constructor in C++ Constructor is a member function with the...
  2. Class In C++ Class in c++ Class is a group of similar object....
  3. Defining Member Function In C++ Class methods definitions  (Defining the member functions) Member functions can...
  4. C++ Functions C++ Functions A function is meant for performing a specified...
  5. Object oriented programming Object oriented programming : The main idea behind object oriented...