Tuesday, May 5, 2009

DESTRUCTOR

A destructor, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. For example, the destructor for the class integer can be defined as shown below:

~constructor name()

{

Statements;

}

Example

~student()

{

cout<<”Student Name:”<<>

}

A destructor never takes any argument and does not return any value. It will be invoked implicitly by the compiler upon exit from the program (or block or function as the case may be ) to clean up storage that is no longer accessible. It is a good practice to declare destructors in a program since it releases memory space for future use.

Whenever new is used to allocate memory in the constructors, we should use delete to free that memory.

For example:



header files

int c=0;

class dest

{

int a;

public:

dest()

{

a=10;

c++;

cout<<”object “ <<>

cout<<”constructed called “<<>

}

~dest()

{

cout<<”object “ <<>

cout<<”destructed called “<<>

c--;

}

};

void main()

{

clrscr();

cout<<” enter main “ <<>

dest obj1, obj2, obj3,obj4;

{

cout<< “block 1” <<>

}

dest obj5;

{

cout<<”re enter main”<<>

}

}

Output will be :

Enter Main

Object 1

Constructed called 10

Object 2

Constructed called 10

Object 3

Constructed called 10

Object 4

Constructed called 10

Block 1

Object 5

Constructed called 10

Object 5

Destructed called 10

Block 2

Object 5

Constructed called 10

Object 5

Destructed called 10

No comments:

Post a Comment