Answers for "c++ assignment operator overload"

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++ overload operator

#include <iostream>

class ExampleClass {
  public:
    ExampleClass() {}
  	ExampleClass(int ex) {
      example_ = 0;
    }
    int&       example()        { return example_; }
    const int& example() const  { return example_; }
  	//Overload the "+" Operator
  	ExampleClass operator+ (const ExampleClass& second_object_of_class) {
    	ExampleClass object_of_class;
    	object_of_class.example() = this -> example() + second_object_of_class.example();
    	return object_of_class;
  	}
  private:
  	int example_;
};

int main() {
  ExampleClass c1, c2;
  c1.example() = 1;
  c2.example() = 2;
  ExampleClass c3 = c1 + c2;
  //Calls operator+() of c1 with c2 as second_object_of_class
  //c3 gets set to object_of_class
  std::cout << c3.example();
}
Posted by: Guest on February-06-2021

Browse Popular Code Answers by Language