C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Object Oriented Programming  >  Destructors
 

Destructors

Destructors are functions that are complimentary to constructors. They de-initialize objects when they are destroyed. A destructor is invoked when an object of the class goes out of scope, or when the memory occupied by it is deallocated using the delete operator.

Declaration of Destructors

A destructor is a function that has the same name as that of the class but is prefixed with a ~(tilde). Overloading a destructor is not possible. It can be explicitly invoked. In other words, a class can have only one destructor. A destructor cannot take arguments or specify a return value, or explicitly return a value.

The following code segment depicts the add class after the inclusion of a destructor:

Class add
{
private:
int iNum1, iNum2, iNum3;
public:
add(int=0; int=0); //Default Argument Constructor, to reduce the number of constructors
void input(int,int);
void sum(void);
~add(void); //Destructor
};

add::~add(void)
{
iNum1 = iNum2 = iNum3 = 0;
}

add::add(int iX = 0, int iY = 0)
{
iNum1 = iX;
iNum2 = iY;
iNum3 = 0;
}

void add::input(int iVar1, int iVar2)
{
iNum1 = iVar1;
iNum2 = iVar2;
}

void add::sum(void)
{
iNum13 = iNum1 + iNum2;
}

void add::disp(void)
{
cout<<”The sum of two numbers is”<<iNum3<<endl;
}


To explicitly call a destructor for an object, the following notation is used:
<object>-><class name>::<destructor>;

The following code explicitly invokes the destructor:
Add *Aptr;
Aptr = new add; //Default constructor
Aptr->add::~add(); //Explictly invoking the destructor

 

 
 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright © 2008 - 3008  CppTutor.com All rights reserved.