Question

#include<iostream>
class A{
    public :
        int a;
};
int main(){
    A obj;
    obj.a = 5;
    A b(obj);

    b.a = 6;
    std::cout<<obj.a;
    return 0;

}

why is the answer returned as 5 , by default copy constructor in C++ returns a shallow copy. Isn't the shallow copy means reference ?? or m i missing something ?

Was it helpful?

Solution

shallow copy means reference ?? or m i missing something ?

You are missing something. Shallow copy means copy. It copies all the members of the object from one to another. It is NOT a reference. The copy created is completely independent of the original

See this excellent tutorial for the difference between shallow and deep copy.

OTHER TIPS

b is a completely separate object from obj. It has its own a independent of obj's.

It sounds like what you have in mind is a reference:

A& b = obj;

After this, both b and obj refer to the same object. Changes made through b would be visible through obj and vice versa.

shallow copy means reference ?? or m i missing something ?

Yes, you're missing something.

Shallow copy doesn't mean reference. Shallow copy means copying the members : if a member is a pointer, then it copies the address, not the content the pointer is pointing to. That means, the pointers in the original object and the so-called copied object point to the same content in memory. That is called shallow copy. Deep copy, on the other hand, doesn't copy the address, it creates a new pointer (in the new object), allocates memory for it, and then copies the content the original pointer points to.

In your case, shallow copy and deep copy make no difference because there are no pointer member(s) in the class. Every member is copied (as usual), and since no member is a pointer, each copied member is a different member in memory. That is, the original object and the copied object are completely different objects in memory. There is absolutely nothing that the two objects share with each other. So when you modify one, it doesn't at all change anything in the other.

Yes, the default copy constructor is a shallow copy. See more here

But, b is completely disjoint from a, so the two things are not related directly.

A b(obj) copies obj information into the newly created object b. Yes it's a shallow copy so b does not actually control what's being assigned to it. What you're probably thinking about is a reference:

A& b = obj;

b.a = 6;

std::cout << obj.a; // 6
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top