Coupon Accepted Successfully!


Dynamic Objects

As discussed earlier, C++ supports dynamic memory allocation/deallocation. C++ allocates memory and initializes the member variables. An object can be created at run time; such an object is called a dynamic object. The construction 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 thedelete operator as follows:
delete ptr;
The delete operator destroys the object pointed by the pointer ptr. It also invokes the destructor of a class. The following program explains the creation and destruction of dynamic objects:

14.15 Write a program to create dynamic object.



class data


int x,y;




cout<<“\n Constructor”;




~data() {cout<<“\n Destructor”;}

void display()
cout<<“\n x=”<<x;
cout<<“\n y=”<<y;

void main()

data *d; // declaration of object pointer
d=new data; // dynamic object
delete d; // deleting dynamic object



The d is a pointer object. The statement d = new data; creates an anonymous object and assign its address to the pointer d. Such an object is called a dynamic object. The constructor is executed when the dynamic object is created. The statement d->display(); invokes the member function, and contents of the members are displayed. The statement delete d; destroys the object by releasing the memory and invoking the destructor.

Test Your Skills Now!
Take a Quiz now
Reviewer Name