C plus plus destructor

C++ Destructor

C++ destructor function gets executed whenever an instance of the class to which it belongs goes out of existence. The primary usage of a C++ destructor function is to release memory space that the instance currently has reserved.
The characteristics of the C++ destructors are as follows:

•Its name is the same as that of the class to which it belongs, except that the first character of the name is the symbol tilde (~).

C++ destructor is declared with no return type (not even void) since it cannot ever return a value.

•It cannot be static, const or volatile.

C++ destructor takes no input arguments, and therefore cannot be overloaded.

•It should have public access in class declaration.

Generally the C++ destructor cannot be called explicitly (directly) from the program. The compiler generates a class to destructor when the object expires. Class destructor is normally used to clean up the mess from an object. Class destructors become extremely necessary when class constructor use the new operator, otherwise it can be given as an empty function. However, the destructor function may be called explicitly allowing you to release the memory not required and allocate this memory to new resources, in Borland C++ version 3.1.

Usage of C++ destructor

The following example illustrates the usage of C++ destructor:
#include<iostream.h>
int count=0;
class alpha
{
public:
alpha()
{
count++;
cout<<”\n No. of object created”<<count;
}
~alpha()
{
cout<<”\n No. of object destroyed”<<count;
count –;
}
};
main()
{
cout<<”Enter MAIN” <<endl;
alpha  A1,A2, A3, A4;
{
cout<<”Enter BLOCK1” <<endl;
alpha A5;
}
{
cout<<”Enter BLOCK2” <<endl;
alpha A6;
}
cout<<”Re- Enter MAIN” <<endl;
Output of the program is as follows:
Enter MAIN
No. of object created 1
No. of object created 2
No. of object created3
No. of object created 4
Enter BLOCK1
No. of object created 5
No. of object created 5
Enter BLOCK2
No. of object created 5
No. of object created 5
Re- Enter MAIN
No. of object created 4
No. of object created 3
No. of object created 2
No. of object created 1
As the objects are created and destroyed, they increase and decrease the count. After the first group of objects is created, A5 is created, and then destroyed; A6 is created, and then destroyed. Finally, the rest of the objects are also destroyed. When the closing brace of the scope is encountered, the C++ destructors for each object in the scope are called. The objects are destroyed in the reverse order of creation.

Comments

  1. SAMEER

    Your Blog is really awesome. I can pass International certification on behalf of you. I am certified Google Adwords Professional. You can donate me whatever you want.I want to earn some part time income Email me for details quyass_pak@hotmail.com

Leave a Reply

Your email address will not be published.