Answers for "c++ copy constructor"

C++
10

create copy constructor c++

// Copy constructor 
    Point(const Point &p2) {x = p2.x; y = p2.y; } 
  
    int getX()            {  return x; } 
    int getY()            {  return y; } 
};
Posted by: Guest on April-26-2020
0

c++ copy constructor

/*
 * The copy constructor in C++ is used to construct one object based on another.
 * Specifically, a 'deep' copy is made, such that any heap-allocated memory
 * is copied fresh. Thus, the copied-to object doesn't rely on the copied-from
 * object after the constructor is called.
 *
 * The copy constructor is called as follows:
 * 
 *  Array a; 
 *  // ... put data in a ...
 *  Array b(a); 
 *
 * See below for implementation details. 
 */

/*
 * Function:   Example copy constructor for an Array class.
 * Parameters: An Array to make a deep copy of
 * Effects:    This is now a deep copy of other
 * Notes:      It's often convenient to use a 'copy' function, as this is also done in the =operator overload.
 */
Array::Array(const Array& other) {
    copy(other);         // make a deep copy of all memory in 'other' to 'this'
}

/*
 * Function:   copy
 * Parameters: An array to make a deep copy of
 * Returns:    None
 * Effects:    Makes a deep copy of other into this. 
 */
void Array::copy(const Array& other) {
	for (int = 0; i < other.len; i++) {
     	this->data[i] = other.data[i]; 
    }
  	this->len = other.len;
}
Posted by: Guest on July-10-2021

Browse Popular Code Answers by Language