Answers for "c++ overloaded 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
2

c++ overloaded == operator

#include <iostream>
#include <string>
 
class Car
{
private:
    std::string m_make;
    std::string m_model;
 
public:
    Car(const std::string& make, const std::string& model)
        : m_make{ make }, m_model{ model }
    {
    }
 
    friend bool operator== (const Car &c1, const Car &c2);
    friend bool operator!= (const Car &c1, const Car &c2);
};
 
bool operator== (const Car &c1, const Car &c2)
{
    return (c1.m_make== c2.m_make &&
            c1.m_model== c2.m_model);
}
 
bool operator!= (const Car &c1, const Car &c2)
{
    return !(c1== c2);
}
 
int main()
{
    Car corolla{ "Toyota", "Corolla" };
    Car camry{ "Toyota", "Camry" };
 
    if (corolla == camry)
        std::cout << "a Corolla and Camry are the same.n";
 
    if (corolla != camry)
        std::cout << "a Corolla and Camry are not the same.n";
 
    return 0;
}
Posted by: Guest on June-17-2020

Browse Popular Code Answers by Language