X
Xiaoshen Li
Dear All,
Sorry for coming back to the old topic. I really cannot understand what
some people has said before. Here I am not interested in clone(), sorry.
In C++, without copy constructor,
MyClass Obj_1 = new MyClass(args);
MyClass Obj_2 = Obj_1;
will make Obj_1 and Obj_2 share the same private object if MyClass has a
private variable which is class type. C++ textbooks say that this
behaviour(shallow copying) is usually un-acceptable. So we need to
provide our own copy constructor, to make sure Obj_1 and Obj_2 have the
identical, but separate private object(deep copying).
In JAVA,
MyClass Obj_1 = new MyClass(args);
MyClass Obj_2 = Obj_1;
will make Obj_1 and Obj_2 two names( two references ) for the same
object. JAVA is happy and accepts such behaviour. It seems to me it is
shallow copying in C++.
My questions is: why C++ cannot accept the shallow copying and JAVA can
and is happy to live with it?
Thank you very much.
Sorry for coming back to the old topic. I really cannot understand what
some people has said before. Here I am not interested in clone(), sorry.
In C++, without copy constructor,
MyClass Obj_1 = new MyClass(args);
MyClass Obj_2 = Obj_1;
will make Obj_1 and Obj_2 share the same private object if MyClass has a
private variable which is class type. C++ textbooks say that this
behaviour(shallow copying) is usually un-acceptable. So we need to
provide our own copy constructor, to make sure Obj_1 and Obj_2 have the
identical, but separate private object(deep copying).
In JAVA,
MyClass Obj_1 = new MyClass(args);
MyClass Obj_2 = Obj_1;
will make Obj_1 and Obj_2 two names( two references ) for the same
object. JAVA is happy and accepts such behaviour. It seems to me it is
shallow copying in C++.
My questions is: why C++ cannot accept the shallow copying and JAVA can
and is happy to live with it?
Thank you very much.