Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor in cpp shallow or deep copy?

Does the default copy-constructor do a shallow or a deep copy in C++?

I am really confused with default copy constructor in cpp, as it does shallow copy or deep copy, as when I did v2=v1; suppose v1={1,2,3}, now if I have done v2[0]=1; It does not get reflected but I heard it does shallow copy, can anybody please explain?

like image 910
Robin Khurana Avatar asked Dec 18 '22 22:12

Robin Khurana


1 Answers

It doesn't do either. It does a memberwise copy. I.e. it copies all the members of the class using their copy constructors. If those members have copy constructors that do a deep copy then you'll get a deep copy, if they do a shallow copy then you'll get a shallow copy, or they could do something else entirely.

Deep copy and shallow copy are not C++ concepts, instead C++ lets you do a deep or shallow copy as you prefer.

like image 105
john Avatar answered Jan 09 '23 02:01

john