The program creates two objects of the Rectangle class, o1 and o2, using a parameterized constructor that takes an integer argument l. The constructor dynamically allocates an array of int of size l and initializes the pointer p to point to the first element of the array.
The second object o2 is created using a copy constructor that takes a reference to another Rectangle object o2. The copy constructor initializes the a member variable with the value of o2.a and creates a new array of int of size a using the new operator. It does not copy the contents of the array pointed to by o2.p. The program then ends, and the destructor is called for each object, which deletes the dynamically allocated memory using the delete[] operator.
However, there is a memory leak in the program because the contents of the array pointed to by p are not copied in the copy constructor, and therefore, the memory allocated for the array in o1 is leaked. To fix this, you can use the std::copy function from the
#include<iostream> using namespace std; class Rectangle { private: int a; int *p; public : Rectangle(int l) //Parameterized Constructor { a=l; p=new int[a]; } Rectangle(Rectangle &o2) { a=o2.a; //p=o2.p; //Not Working p=new int[a]; } ~Rectangle(){ cout<<"Deallocated"; } }; int main() { Rectangle o1(5),o2(o1); return 0; }To download raw file Click Here
DeallocatedDeallocated
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions