Whats in this post?
- Background and Explanation of the code
To copy code: Click “View Source” on the right of this code snippet.
Background and Explanation of the code
The above program create and destroy a dynamic object of class rectangle.The statement rectangle *ptr; creates a pointer variable ptr that can point to an object of type rectangle.Initially it contains a garbage value.The statement
ptr = new rectangle;
creates a nameless object of class rectangle at run time, calls the constructor with no parameter and returns the starting address which is stored in pointer variable ptr.The statement
ptr -> read ( );
calls the member function read ( ) of class rectangle through ptr which points to dynamic object.Similarly the next statement;
ptr -> show ( );
displays the data members of dynamic object.
The statement delete ptr ; calls the destructor which destroys the object currently referred by pointer ptr and this memory which gets freed can be reused.Thus , using delete operator, the programmer can destroy the object explicitly anywhere in the program as per the requirement.Hence, the lifetime of the dynamic object can be controlled by the programmer.
Constructor with no parameter invoked
Enter length and breadth = 4 6
Area of rectangle = 24
End of program