The Wayback Machine - https://web.archive.org/web/20241109012453/https://www.geeksforgeeks.org/shallow-copy-and-deep-copy-in-c/
Open In App

Shallow Copy and Deep Copy in C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. There are two ways that are used by C++ compiler to create a copy of objects.

// Copy Constructor
Geeks Obj1(Obj);
or
Geeks Obj1 = Obj;

// Default assignment operator
Geeks Obj2;
Obj2 = Obj1;

Depending upon the resources like dynamic memory held by the object, either we need to perform Shallow Copy or Deep Copy in order to create a replica of the object. In general, if the variables of an object have been dynamically allocated, then it is required to do a Deep Copy in order to create a copy of the object but one may wonder what is the shallow copy and deep copy? Don’t worry, GeeksforGeeks got you covered.

In this article, we will learn what is shallow copy, what is deep copy, how they are different from each other, where they happen by default and where we need one over another.

Understanding the difference between shallow and deep copies is crucial for managing memory effectively. The C++ Course explains these concepts in detail, ensuring you can use them appropriately in your applications.

What is Shallow Copy?

In shallow copy, an object is created by simply copying the data of all variables of the original object. This works well if none of the variables of the object are defined in the heap section of memory but if some variables are dynamically allocated memory from heap section, then the copied object variable will also reference the same memory location.

This will create ambiguity and run-time errors, dangling pointer. Since both objects will reference to the same memory location, then change made by one will reflect those change in another object as well. Since we wanted to create a replica of the object, this purpose will not be filled by Shallow copy. 

Note: C++ compiler implicitly creates a copy constructor and overloads assignment operator in order to perform shallow copy at compile time.

Consider the below objects B1 and B2, having integer data members representing dimensions of a 3d box.

shallow-copy-in-cpp-1

Now imagine one of the members is a pointer to the integer variable. Here, the shallow copy will only copy the address stored in the pointer leading both the object member pointing to the same object.

shalllow-in-cpp-2

Below is the implementation of the above example:

C++
// C++ program for the above approach
#include <iostream>
using namespace std;

// Box Class
class box {
private:
    int length;
    int breadth;
    int height;
      int *p;

public:
    // Function that sets the dimensions
    void set_dimensions(int length1, int breadth1,
                        int height1,int x)
    {
        length = length1;
        breadth = breadth1;
        height = height1;
          p=new int;
      *p=x;
    }

    // Function to display the dimensions
    // of the Box object
    void show_data()
    {
        cout << " Length = " << length
             << "\n Breadth = " << breadth
             << "\n Height = " << height
             << "\n P int pointing to = "<<p
             << endl;
    }
};

// Driver Code
int main()
{
    // Object of class Box
    box B1, B3;

    // Set dimensions of Box B1
    B1.set_dimensions(14, 12, 16,100);
    B1.show_data();

    // When copying the data of object
    // at the time of initialization
    // then copy is made through
    // COPY CONSTRUCTOR
    box B2 = B1;
    B2.show_data();

    // When copying the data of object
    // after initialization then the
    // copy is done through DEFAULT
    // ASSIGNMENT OPERATOR
    B3 = B1;
    B3.show_data();

    return 0;
}

Output
Length = 14
 Breadth = 12
 Height = 16
 Length = 14
 Breadth = 12
 Height = 16
 Length = 14
 Breadth = 12
 Height = 16

What is Deep Copy?

In Deep copy, an object is created by copying data of all variables, and it also allocates similar memory resources with the same value to the object. In order to perform Deep copy, we need to explicitly define the copy constructor and assign dynamic memory as well, if required. Also, it is required to dynamically allocate memory to the variables in the other constructors, as well.

Consider the previous example again. If we deep copy the object, then each object will have their own copy of the data pointed by the breadth pointer.

deep-copy-in-cpp

Below is the implementation of the above example:

C++
// C++ program to implement the
// deep copy
#include <iostream>
using namespace std;

// Box Class
class box {
private:
    int length;
    int* breadth;
    int height;

public:
    // Constructor
    box()
    {
        breadth = new int;
    }

    // Function to set the dimensions
    // of the Box
    void set_dimension(int len, int brea,
                       int heig)
    {
        length = len;
        *breadth = brea;
        height = heig;
    }

    // Function to show the dimensions
    // of the Box
    void show_data()
    {
        cout << " Length = " << length
             << "\n Breadth = " << *breadth
             << "\n Height = " << height
             << endl;
    }

    // Parameterized Constructors for
    // for implementing deep copy
    box(box& sample)
    {
        length = sample.length;
        breadth = new int;
        *breadth = *(sample.breadth);
        height = sample.height;
    }

    // Destructors
    ~box()
    {
        delete breadth;
    }
};

// Driver Code
int main()
{
    // Object of class first
    box first;

    // Set the dimensions
    first.set_dimension(12, 14, 16);

    // Display the dimensions
    first.show_data();

    // When the data will be copied then
    // all the resources will also get
    // allocated to the new object
    box second = first;

    // Display the dimensions
    second.show_data();

    return 0;
}

Output
Length = 12
 Breadth = 14
 Height = 16
 Length = 12
 Breadth = 14
 Height = 16

Difference between the Shallow Copy and Deep Copy

The below table list the differences between the shallow copy and the deep copy in the tabular form:

 S.No.Shallow Copy Deep copy
1.When we create a copy of object by copying data of all member variables as it is, then it is called shallow copy When we create an object by copying data of another object along with the values of memory resources that reside outside the object, then it is called a deep copy
2.A shallow copy of an object copies all of the member field values. Deep copy is performed by implementing our own copy constructor.
3.In shallow copy, the two objects are not independentIt copies all fields, and makes copies of dynamically allocated memory pointed to by the fields
4.It also creates a copy of the dynamically allocated objectsIf we do not create the deep copy in a rightful way then the copy will point to the original, with disastrous consequences.





Previous Article
Next Article

Similar Reads

Difference Between Shallow copy VS Deep copy in Pandas Dataframes
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Difference between Shallow and Deep copy of a class
Shallow Copy: Shallow repetition is quicker. However, it's "lazy" it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each of the first and therefore the copy can have pointers that reference constant underlying knowledge. Deep C
5 min read
How to Implement a Copy Constructor for Deep Copying?
In C++, the copy constructor enables us to initialize an object using another object of the same class. In this article, we will learn, how to implement a copy constructor for deep copying. Implementing a Copy Constructor for Deep CopyingIn C++, a copy constructor is used to create a copy of an object from an existing object of the same class. By d
3 min read
Difference between Hard Copy and Soft Copy
1. Hard Copy : Hard copy refers to the digital document file which is printed on paper or other material like transparency. In hard copy the output is printed on the paper and sometimes it is referred as permanent copy. We can touch the hard copy. We can say it is a physical copy. For example- News Paper, Book, Notebook, printed document files, etc
3 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header <algorithm>. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Difference between Deep Web and Dark Web
Prerequisite - Deep web, Dark web, and DarkNet Deep Web: It is the web that cannot be accessed by the search engines, like government private data, bank data, cloud data, etc. These data are sensitive and private, so kept out of reach. It is used to provide access to a specific group of people. On the dark Web, users do intentionally bury data. Dar
3 min read
Difference between a Neural Network and a Deep Learning System
Since their inception in the late 1950s, Artificial Intelligence and Machine Learning have come a long way. These technologies have gotten quite complex and advanced in recent years. While technological advancements in the Data Science domain are commendable, they have resulted in a flood of terminologies that are beyond the understanding of the av
7 min read
Difference Between Artificial Intelligence vs Machine Learning vs Deep Learning
Artificial Intelligence is basically the mechanism to incorporate human intelligence into machines through a set of rules(algorithm). AI is a combination of two words: "Artificial" meaning something made by humans or non-natural things and "Intelligence" meaning the ability to understand or think accordingly. Another definition could be that "AI is
14 min read
When Does Compiler Create Default and Copy Constructors in C++?
A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++ Default ConstructorCopy constructorParameterized ConstructorIn C++, the compiler creates a default constructor if we d
3 min read
Difference between Lodash _.clone() method and '=' operator to copy Objects
In this article, we will learn about the difference between using the _.clone() method in Lodash and using the '=' operator to copy objects. Both of these methods are used to create a copy of an object in JavaScript. However, both work in very different ways. Using _.clone() Method: The _.clone() method creates a new object and copies each value fr
3 min read
Difference between the COPY and ADD commands in a Dockerfile
When creating Dockerfiles, it's often necessary to transfer files from the host system into the Docker image. These could be property files, native libraries, or other static content that our applications will require at runtime. The Dockerfile specification provides two ways to copy files from the source system into an image: the COPY and ADD dire
4 min read
Copy-and-Swap Idiom in C++
Before going into deep let us first have a look on the normal 'overloaded assignment operator' that we use. C/C++ Code // Simple C++ program to demonstrate overloading of // assignment operator. #include <cstring> #include <iostream> using namespace std; class anyArrayClass { int size; int* ptr; public: // Initializer list anyArrayClass
3 min read
Copy File To Vector in C++ STL
Prerequisite: Vectors in C++ STLFile Handling in C++ The C++ Standard Template Library (STL) provides several useful container classes that can be used to store and manipulate data. One of the most commonly used container classes is the vector. In this article, we will discuss how to copy the contents of a file into a vector using C++ STL. Approach
2 min read
Different ways to copy a string in C/C++
Copying a string is a common operation in C/C++ used to create a duplicate copy of the original string. In this article, we will see how to copy strings in C/C++. Methods to Copy a String in C/C++1. Using strcpy() We can use the inbuilt function strcpy() from <string.h> header file to copy one string to the other. strcpy() accepts a pointer t
15+ min read
How to copy elements of an Array in a Vector in C++
An Array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Following are the
6 min read
C++ Program to Copy One File into Another File
To copy the text/contents of one file to another file, we should know the basics of reading and writing a text file in C++. To copy the file using C++, we read the contents of the source file and write it into the destination file. Steps to copy one file to another in C++: Create objects of ifstream and ofstream classes.Check if they are connected
2 min read
C++ Program to Copy the Contents of One File Into Another File
Here, we will see how to develop a C++ program to copy the contents of one file into another file. Given a text file, extract contents from it and copy the contents into another new file. After this, display the contents of the new file. Approach:Open the first file which contains data. For example, a file named "file1.txt" contains three strings o
2 min read
C++ Program to Copy the Contents of One Array Into Another in the Reverse Order
Given an array, the task is to copy these array elements into another array in reverse array.Examples: Input: array: 1 2 3 4 5 Output: 5 4 3 2 1 Input: array: 10 20 30 40 50 Output: 50 40 30 20 10 Let len be the length of original array. We copy every element original_arr[i] to copy_arr[n-i-1] to get reverse in copy_arr[]. C/C++ Code // C program t
2 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
Preventing Object Copy in C++ (3 Different Ways)
Many times, user wants that an instance of a C++ class should not be copied at all. So, the question is how do we achieve this ? There are three ways to achieve this : Keeping the Copy Constructor and Copy assignment operator as private in the class. Below is the C++ implementation to illustrate how this can be done. #include <iostream> using
3 min read
How to Copy a Stack in C++?
In C++, stacks are a type of container adaptor with a LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we are going to discuss how to copy a stack in C++. Copying a Stack to Another in C++To copy a std::stack, we can simply use the copy constructor
2 min read
Copy Elision in C++
Copy elision (also known as copy omission) is a compiler optimization method that prevents objects from being duplicated or copied. It makes 'returning by value' or 'pass-by-value' feasible in practice. In simple terms, the compiler prevents the making of extra copies which results in saving space and better the program complexity(both time and spa
4 min read
How to Copy a Vector to an Array in C++?
In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements. Sometimes, we may need to copy the contents of a vector to the POD array. In this article, we will learn how to copy a vector to an array in C++. Example: Input: myVec = {10,20,30,40,50,60};Output: array: {10,20,30,40,50,60}Convert Vector to an Array in C++ For
2 min read
How to Implement a Copy Constructor in a Derived Class in C++
In object-oriented programming, a copy constructor is a special member function that initializes a new object as a copy of an existing object. In this article, we will learn how to implement a copy constructor in a derived class. Implementing Copy Constructor in a Derived Class in C++ In C++, when we implement a constructor in an inherited class, w
3 min read
How to Copy One Array to Another in C++?
In C++, arrays are a type of data structure that stores a fixed-size collection of elements of the same type in a contiguous memory location, and sometimes we need to copy the contents of one array to another. In this article, we will learn how to copy one array to another in C++. Example: Input: arr1 = {10, 20, 30, 40, 50, 60} Output: arr2: {10, 2
2 min read
How to Copy a One Deque to Another in C++?
In C++, STL provides a container called deque (short for double-ended queue) that allows fast insertion and deletion at both its beginning and its end. In some scenarios, we may need to copy the contents of one deque to another. In this article, we will learn how to copy one deque to another in C++. Example: Input: deque1 = {10, 20, 30, 40, 50, 60}
2 min read
When is a Copy Constructor Called in C++?
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value
2 min read
How to Declare a Copy Constructor in a Derived Class?
In C++, a copy constructor is a constructor that initializes an object as a copy of an existing object of the same class. In this article, we will learn how to declare a copy constructor in a derived class. Declaring a Copy Constructor in a Derived ClassWe can declare a copy constructor in a derived class by declaring a function with the same name
3 min read
How to Copy a List in C++ STL?
In C++, a list is a sequence container provided by the STL library that represents a doubly linked list and allows us to store data in non-contiguous memory locations efficiently. In this article, we will learn how to copy one list to another in C++. Input: sourceList = {10, 20, 30, 40, 50};Output: copiedList = {10, 20, 30, 40, 50};Copying a List t
2 min read
C++ 23 - Header[Testing Demo Copy]
Data Visualization is a technique of presenting data graphically or in a pictorial format which helps to understand large quantities of data very easily. This allows decision-makers to make better decisions and also allows identifying new trends, patterns in a more efficient way. In this tutorial, we will look at different modules provided by Pytho
7 min read
three90RightbarBannerImg