operator overloading = modifies original object

  • A+
struct List {     int size;     int* items;     List& operator=(const List& l); };  List& List::operator=(const List& l) {     delete[] items;     size = l.size;     items = new int[20];      for (int i = 0; i < size; i++)         items[i] = l.items[i];      return *this; }  ostream& operator<<(ostream& out, const List& l) {     out << "Size: " << l.size << "/t {";     for (int i = 0; i < l.size; i++)         out << l.items[i] << " ";      return (out << "}"); }  int main() {     int size = 6;     List l1 = { size, new int[size]{ 0, 1, 2, 3, 4, 5 } };     List l2 = l1;      l2.items[1] = 50;      cout << l1 << endl;     cout << l2 << endl;      return 0; } 

I'm confused since when I assign l2 = l1 by using an overloaded operator, why does the contents of l1 change, when altering l2 later on? Especially since l1 is passed as a const. They somehow point to the same object in memory instead of being a copy.


List l2 = l1; 

Despite the =, because this is a declaration you're performing copy construction (formally "copy-initialisation"), which has nothing to do with the assignment operator.

You didn't define a copy constructor (which should look much like your copy assignment operator), so the pointers are indeed shared.

The results would have been what you expected, had you written:

List l2{}; l2 = l1; 

By the way, I'd give size and items defaults (0 and nullptr respectively), if I were you. Otherwise, when you forget that {}, the members have unspecified values and all hell breaks loose. This could be done with a nice default constructor, or by forgetting this whole enterprise and using a std::vector instead ;)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: