This program is an example of using dynamic memory allocation to create an object on the heap. The new keyword is used to allocate memory for a new Rectangle object on the heap, and the address of the newly created object is stored in the pointer variable h.
The program also shows an example of using a pointer to access an object on the stack. The address of the r object is assigned to the pointer variable p, and the -> operator is used to access the member variables and member functions of the object through the pointer.
Overall, this program demonstrates the flexibility of object-oriented programming in C++, where objects can be created on the stack or the heap and accessed through pointers.
#include<iostream> using namespace std; class Rectangle { public : int length; int breadth; int area() { return length*breadth; } int perimeter() { return 2*(length+breadth); } }; int main() { Rectangle r,*p;//Using Stack p=&r; p->length=5; p->breadth=10; cout<<"Stack Area : "<<p->area()<<endl; Rectangle *h=new Rectangle(); //Using Heap h->length=10; h->breadth=10; cout<<"Heap Area : "<<h->area(); return 0; }To download raw file Click Here
Stack Area : 50 Heap Area : 100Stack Area : 50 Heap Area : 100
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions