Page 136 - DCAP404 _Object Oriented Programming
P. 136
Unit 6: Constructors and Destructors
6.6 Destructors Notes
Constructors create an object, allocate memory space to the data members and initialize the data
members to appropriate values; at the time of object creation. Another member method called
destructor does just the opposite when the program creating an object exits, thereby freeing the
memory.
A destructive method has the following characteristics:
1. Name of the destructor method is the same as the name of the class preceded by a tilde(~).
2. The destructor method does not take any argument.
3. It does not return any value.
The following codes snippet shows the class abc with the destructor method;
class abc
{
int x,y;
public:
abc();
abc(int);
abc(int, int);
~abc()
{
cout << “Object being destroyed!!”;
}
}
Whenever an object goes out of the scope of the method that created it, its destructor method is
invoked automatically. However if the object was created using new operator, the destructor
must be called explicitly using delete operator. The syntax of delete operator is as follows:
delete(object);
Notes Whenever you create an object using new keyword, you must explicitly destroy it
using delete keyword, failing which the object would remain homed in the memory and
in the course of program execution there may come a time when sufficient memory is not
available for creation of the more objects. This phenomenon is referred to as memory
leak. Programmers must consider memory leak seriously while writing programs for the
obvious reasons.
Did u know? What’s the order that objects in an array are destructed?
In reverse order of construction: First constructed, last destructed.
In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:
void userCode()
{
Fred a[10];
...
}
LOVELY PROFESSIONAL UNIVERSITY 129