'=' performs deep or shallow copy?

Aug 25, 2013 at 2:25pm
From what I learnt in Java, if you have 2 objects, and you use the default assignment operator between them "=", you only perfom a shallow copy where only the address is copied.

But is it the same in C++?
Let's say we have:
1
2
3
4
A cAObject1;
A cAObject2;

cAObject1 = cAObject2;


Identifiers cAObject1- and 2, are not adresses like in Java right? They are literally the memory of the objects. So the =-operator does a deep copy in C++ then or how does this work?
Aug 25, 2013 at 2:37pm
Yes and no. Memory has been allocated from somewhere for each object. That memory has space for the member variables of the object too. The copy assignment essentially does a deep copy.

However, for the member pointer variables such "deep" copy copies only the stored address, and thus the default copy assignment generated by compiler achieves only a shallow copy. If one has pointer members in a class, then one usually has to write explicit copy constructor, copy assingment, and destructor.
Aug 25, 2013 at 3:01pm
Thank you for the good explanation :). I see what you mean.
Aug 25, 2013 at 5:41pm
If you wanted to do a "shallow" copy in C++ (where you just copy the address) you can use pointers:

A* cAObject1 = new A();
A* cAObject2;

cAObject2 = cAObject1;

The only difference is that you need to clean-up after yourself whenever you use new as there is no garbage collector, and you access members with -> instead of with ..
Topic archived. No new replies allowed.