c ++ programmer-defined copy constructor

Dynamically allocate memory constructors, programmers need to write your own copy constructor, if the default constructor will be problems.

The programmer can define the copy constructor of a class. Programmer-defined copy constructor must have a parameter which is a reference to the same class . Example Prototype:

  NumberArray :: NumberArray(NumberArray &obj)

  {

    arraySize = obj.arraySize;

    aPtr = new double[arraySize];

    for(int index = 0; index < arraySize; index++)

    {

      aPtr[index] = obj.aPtr[index];

    }

  }

 

Note: There must be a copy constructor parameter, the parameter is a reference to the same class. If you forget identifier & reference parameters will cause a compiler error. Further, the parameter should be a const reference, because the copy constructor should not modify the copied object.

Whenever passing objects by value in the function call, the compiler will automatically call the copy constructor to create a copy of the object. It is for this reason, copy constructor shape parameters must be passed by reference; because, if passed by value when the constructor is called, the constructor is called again immediately to create a copy of the pass-by-value, leading to the constructor calls the endless chain.

1. Copy the constructor call

Whenever an object is created, and using another object of the same class to initialize it, the system will automatically call the copy constructor, an example:

  Rectangle box(5, 10);

  Rectangle b = box; // initialization statement

  Rectangle b1 (box); // initialization statement

When receiving a call to a function of class type parameter, it will automatically copy constructor call. E.g:

  void fun(Rectangle rect)

  { 

  }

Assuming the following statement to call it: fun (fox);

This will cause the Rectangle copy constructor is called. Finally, as long as the value of the object returned by the function class will automatically call the copy constructor. Therefore, in the following function, when a return statement is executed it will call the copy constructor:

Rectangle makeRectangle()

{

  Rectangle rect(12,3);

  return rect;

}

This is because the return statement must create a temporary non-local copy of that object, so that after the function returns, the caller can use the copy. In summary, a copy constructor class will be called in the following case:

1) variable is used to initialize an object of the same class.

2) the value of the reference function is used to call the class type.

3) function returns the value of the object is a class.

Note: When press-shaped reference or pointer to pass a class reference, copy constructor will not be called. Further, when the function returns a reference or pointer to the object, it does not call the copy constructor.

 

Guess you like

Origin www.cnblogs.com/ruigelwang/p/12626880.html