dynamic creation and destruction of objects in C++
-> C++ supports dynamic memory allocation and deallocation. c++ allocates memory and initializes the member variable.An object can be created at run time; such an object called an dynamic object.the constuction and destruction of the dynamic object is explicitly done by the programmer. The new and delete operators are used to allocate and deallocate memory to such objects. A dynamic object can be created using the new operator as follows:
ptr= new classname;
-> The new operator returns the address of the object created, and it is stored in the pointer ptr. the variable ptr is a pointer object of the same class. The member variable of the object can be accessed using the pointer and -> (arrow) operator. A dynamic object can be destroyed using delete operator:
delete=ptr;
-> The delete operator destroys the object pointed by the pointer ptr. it also invokes the destructor of a class. following program explains the creation and destruction of dynamic objects:
// C++ program on the creation and destruction of dynamic objects.
-> C++ supports dynamic memory allocation and deallocation. c++ allocates memory and initializes the member variable.An object can be created at run time; such an object called an dynamic object.the constuction and destruction of the dynamic object is explicitly done by the programmer. The new and delete operators are used to allocate and deallocate memory to such objects. A dynamic object can be created using the new operator as follows:
ptr= new classname;
-> The new operator returns the address of the object created, and it is stored in the pointer ptr. the variable ptr is a pointer object of the same class. The member variable of the object can be accessed using the pointer and -> (arrow) operator. A dynamic object can be destroyed using delete operator:
delete=ptr;
-> The delete operator destroys the object pointed by the pointer ptr. it also invokes the destructor of a class. following program explains the creation and destruction of dynamic objects:
// C++ program on the creation and destruction of dynamic objects.
#include <iostream>
using namespace std;
class Test
{
private:
~Test()
{
cout << "Destroying Object\n";
}
public:
Test()
{
cout << "Object Created\n";
}
friend void destructTest(Test* );
};
void destructTest(Test* ptr)
{
delete ptr;
cout << "Object Destroyed\n";
}
int main()
{
Test *ptr = new Test;
// destruct the object to avoid memory leak
destructTest(ptr);
return 0;
}
using namespace std;
class Test
{
private:
~Test()
{
cout << "Destroying Object\n";
}
public:
Test()
{
cout << "Object Created\n";
}
friend void destructTest(Test* );
};
void destructTest(Test* ptr)
{
delete ptr;
cout << "Object Destroyed\n";
}
int main()
{
Test *ptr = new Test;
// destruct the object to avoid memory leak
destructTest(ptr);
return 0;
}
OUTPUT:
Object Created
Destroying Object
Object Destroyed