Search code examples
c++algorithmcopy-constructordefault-copy-constructor

c++ copy constructor related query


#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 ?


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.