Answers for "new operator overloading in c++"

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
1

c++ over load operator

// This will substract one vector (math vector) from another
// Good example of how to use operator overloading

vec2 operator - (vec2 const &other) {
    return vec2(x - other.x, y - other.y);
}
Posted by: Guest on February-12-2021

Code answers related to "new operator overloading in c++"

Browse Popular Code Answers by Language