Dynamic Creation and Destruction of Objects
Q21. Explain about the dynamic creation and destruction of objects.
Answer:
The objects in C++ are dynamically created and destroyed by using new and delete operators.
(i) new Operator
An object can be dynamically created by using a new operator that returns a pointer to it. A default constructor is called for the newly created object.
A special pointer called a NULL pointer is returned by the new operator if the requested memory is not available.
An object created by new is alive till delete is encountered.
General Form
pointer variable = new data type
Example
int *ptr = new int;
In the above example, ptr is a pointer variable of type ‘int’ created by using a ‘new’ operator.
Pointer variable declaration along with the initialization can be done as,
int *ptr = new int(10);
Applications
- It can be used along with the classes and structures to allocate the memory.
- It can also be used for creating multidimensional array, where the size of the error must be provided.
Advantages:
- It finds the size of the object automatically without using the size operator.
- Initializing the objects at the time of their declarations is allowed by the new operator.
Program
#include<iostream.h>
#include <conio.h>
int main()
{
int *p; //declaration of an integer
// pointer variable
clrscr( );
p=new int[15]; //allocation of
memory for 15
//integer values
if(p=NULL)
cout<< "\n Memory space
is released";
else
cout<< "\n Memory space
is allocated”;
getch();
return 0;
}
Output
(ii) delete Operator
This operator is used to deallocate the memory which was allocated by the new operator thereby destroying the object. The memory-is then released to the heap so that it can be utilized by some other object.
General Form
delete pointer variable;
Example
delete P;
For array,
delete [size] P;
Where,
size = size of the array ‘P’. If no size is specified then the entire array 'P’ gets deleted.
When delete statement is encountered it calls the destructor apart. from deallocating the memory.
Program
#include<iostream.h>
#include <conio.h>
int main()
{
int *p; //declaration of an
integer
// pointer variable :
clrscr( );
p=new int [15]; //allocation of
memory for 15
//integer values
if(p==NULL)
cout<< "\n Memory space
is released",
else
cout<< "\n Memory space
is allocated";
delete p;//frees memory space
allocation by new operator
getch();
return 0;
}
Output