Answers for "c++ assignment operator"

C++
1

c++ assignment operator overload

/*
 * Assignment operator overload in C++ is used to copy one object into another.
 * Specifically, a 'deep' copy is made, such that any heap-allocated memory
 * in the copied-from object is copied fresh to the copied-to object. Note also
 * that the copied-to object ('this') must deallocated any of its own 
 * heap-allocated memory prior to making the copy. 
 * 
 * The assignment operator overload is called as follows:
 * 
 *  Array a; 
 *  Array b;
 *  // ... put data in b / a ...
 *  a = b;    // a now becomes a deep copy of b. 
 *
 * See below for implementation details. 
 */

/*
 * Function:   Example assignment operator overload for an Array class.
 * Parameters: An Array to make a deep copy of
 * Returns:    A reference to the data in this (for chained assignment a = b = c)
 * Effects:    This is now a deep copy of other
 */
Array& Array::operator=(const Array& other) {
  if (this != &other) {  // ensure no self-assignment (i.e. a = a)
    clear();             // deallocate any heap-allocated memory in 'this'
    copy(other);         // make a deep copy of all memory in 'other' to 'this'
  }
  return *this;          // return the data in 'this' 
}

/* 
 *  Function:   clear
 *  Parameters: None
 *  Returns:    None
 *  Effects:    Deallocates heap-allocated memory associated with this object.
 */
void Array::clear() { delete [] data; }

/*
 * 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
0

assignment operator with pointers c++

class Array
{
public:
    Array(int N)
    {
         size = N;
         arr = new int[N];
    }

    //destructor
    ~Array()
    {
        delete[] arr;
    }

    //copy constructor
    Array(const Array& arr2)
    {
        size = arr2.size;
        arr = new int[size];
        std::memcpy(arr, arr2.arr, size);
    }

    //overload = operator
    Array& operator=(const Array& arr2) 
    {
        if (this == &arr2)
            return *this; //self assignment
        if (arr != NULL)
            delete[] arr; //clean up already allocated memory

        size = arr2.size;
        arr = new int[size];
        std::memcpy(arr, arr2.arr, size);
        return *this;
    }

private:
    int size;    //array elements
    int *arr;    //dynamic array pointer
};
Posted by: Guest on August-19-2020

Browse Popular Code Answers by Language