Are array members deeply copied in C++?


In case of C/C++, we can be able to assign a struct (or class in C++ only) variable to another variable of same type. At the time when we assign a struct variable to another, all members of the variable are copied to the other struct variable. In this case the question is arisen what happens when the structure consists of an array?

Now, we have to discuss about arrays. Main point to note is that the array members is not copied as shallow copy; compiler automatically accomplishes Deep Copy in case of array members. In the below program, struct test consists of array member str1[]. When we are able to assign st1 to st2, st2 has a new copy of the array. So st2 is not modified or changed when we modify or change str[] of st1.

Example

 Live Demo

# include <iostream>
# include <string.h>
using namespace std;
struct test{
   char str1[20];
};
int main(){
   struct test st1, st2;
   strcpy(st1.str1, "Tutorial Point");
   st2 = st1;
   st1.str1[0] = 'X';
   st1.str1[1] = 'Y';
   /* Because copy was Deep, both arrays are different */
   cout<< "st1's str = " << st1.str1 << endl;
   cout<< "st2's str = " << st2.str1 << endl;
   return 0;
}

Output

st1's str = XYtorial Point
st2's str = Tutorial Point

Therefore, in case of C++ classes, we don’t require to write our own copy constructor and assignment operator for array members because the default behavior is Deep copy for arrays.

Updated on: 29-Jan-2020

731 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements