Hello, can you explain on your fingers why you need a copy constructor? Its meaning is not quite clear. (

    2 answers 2

    The copy constructor is needed to create a copy of the object, and it is also safe. Sometimes a bit-copy may be useful, but in most cases it is not suitable, for example, when an object owns some resources that are released in the destructor. For example, if you write this code:

    struct A { A(int a) { ptr = new int(a); } ~A() { delete ptr; } A(const A& obj) { ptr = obj.ptr; } int* ptr; }; A obj1(10); A obj2 = obj1; 

    then the same pointer will be released first in the destructor of the obj1 object, and then in the destructor of the obj2 object, which will lead to an error. It would be more correct to make the copy constructor like this:

     A(const A& obj) { ptr = new int(*obj.ptr); } 

    Then each object will have its own unique pointer.

    • obj is a pointer? - Alerr

    To create a new object on the basis of an existing one, thereby automatically initializing a new object with data from the one on which the copy is made.