Understanding copy constructors in C++

   The function of the copy constructor is to use an existing object to initialize the same object that was created. It is a special constructor with all the characteristics of the general constructor. When a new object is created, the system will automatically call it; Its formal parameter is a reference to the object of this class, and its special function is to copy the object represented by the parameter to the newly created object field by field.

 Users can define specific copy constructors according to actual needs to realize the transfer of data members between objects of the same type. If the user does not declare a copy constructor of the class, the system will automatically generate a default copy constructor, whose function is to copy the value of each data member of the initial object to the newly created object. It is defined as: class name (class name & object name)

class dog
{
private:

    int age;
    float weight;
    char *color;

public:
    dog();
    dog(dog&);
    void play();
    void hunt();

};

dog::dog(dog&other)
{
   age   = other.age;
   weight = other.weight;
   color  = other.color;
}

  

   The copy constructor is called in the following four cases:

  (1) Use an object of the class to initialize another object:

    dog dog1;

  dog dog2(dog1);

  (2) Another form of initializing another object with an object of a class:

  dog dog2 = dog1;

  (3) The object is passed as a parameter and the copy constructor is called:

  f(dog a){}

    dog b;

       f(b);

  (4) If the return value of the function is an object of the class, when the function call returns, the copy constructor is called

  dog f{

       dog a;

       .....

      return a;

  }

      dog b;

      b = f();

// copy constructor is divided into deep copy and shallow copy

Shallow copy only copies the space of the object without copying the resources, while the deep copy needs to copy the space of the object and the resources at the same time.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325160636&siteId=291194637