0

Consider the following piece of code

class A{
  public:
     int val;
     a(); 
}
int main(){
     A obj1;
     A obj2=obj1;
}

In this case, there are no pointers or heap involved. Will this A obj2=obj1 be shallow copy or deep copy? When I use addressof() function on obj1 and obj2 I get different values.

wallyk
  • 56,922
  • 16
  • 83
  • 148
  • Does this answer your question? [What is the difference between a deep copy and a shallow copy?](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy) – prehistoricpenguin Jul 19 '21 at 01:20

1 Answers1

2

There's actually no such thing as a shallow copy here, because copying an object of type A will always copy val.

But with a class like this:

class B
{
    char *s;
};

you can make either a shallow copy or a deep copy, depending on whether you copy just the pointer s (shallow), or whether a copy is made of what s is pointing to (deep). In the case of a deep copy, the value of s is different in the copy, of course, because it ends up pointing at a different chunk of memory to the original.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
  • Thanks for your answer! So can we call **A obj2=obj1** deep copy? – Bill Indie Jul 19 '21 at 07:14
  • In effect, although when you copy an object that contains only primitive data types then all you can do is copy the entire object (unless you write some kind of funky copy constructor that does something weird), so there's really no distinction. But be careful. `B obj2 = obj1` would be a shallow copy, unless you write a copy constructor that copies what `s` is pointing to into newly allocated storage. – Paul Sanders Jul 19 '21 at 22:10