The dynamic object can be created by the execution of a new operator expression. The syntax for creating a dynamic object is shown above. It returns the address of a newly created object. The returned address of an object can be stored in a variable of type pointer to object.
While creating a dynamic object, if a class has the default constructor, it is invoked as a part of object creation activity. Once a pointer is holding the address of a dynamic object, its members can be accessed by using -> operator.
The syntax of delete operator releasing memory allocated to dynamic object is as
follows:
delete pointer_to_object
it destroys the object pointed to by pointer_to_object variable. It also invokes the destructor of the class if it exists as a part of object destruction activity before releasing memory allocated to an object by the new operator.
Sample Program
#include <iostream.h>
class de
{
public:
int data1;
char data2;
de(void)
{
cout<<”Constructor”<<endl;
data1 = 1;
data2 = ‘A’;
}
~de()
{
cout<<”Destructor”<<endl;
}
void show(void)
{
cout<<data1<<data2<<endl;
}
};
void main()
{
de *ptr_obj;
ptr_obj = new de;
cout<<”Accessing through dynamic object”<<endl;
ptr_obj->show();
cout<<”Destroying the dynamic object”<<endl;
delete ptr_obj;
}
No comments:
Post a Comment