I'm learning C++ and in book section about overloading operator =, it says: "we need to free the old space and assign new values to each data element". My question is: why we need to deallocate memory when it's going to be overwritten anyway? Why can't we simply increment pointers and write to same memory (and data will be of same size since we'll assigning object to an object of a same type)? EDIT: Code from a book:
template <class T> Vec<T>& Vec<T>::operator=(const Vec& rhs) { // check for self-assignment if (&rhs != this) { // free the array in the left-hand side uncreate(); // copy elements from the right-hand to the left-hand side create(rhs.begin(), rhs.end()); } return *this; }