Copy Constructor Example in C++


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 header to copy the contents of the array in the copy constructor. Also, you should implement the copy assignment operator to ensure correct behavior when assigning one object to another.

Source Code

#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

Output

DeallocatedDeallocated

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples