Why does this happen? The default assignment operator produces a shallow i.e.
bit-by-bit) copy of the argument (on the right hand side of the = operator), but not of
the dynamically allocated memory. To make sure that we get a complete copy of a
class instance, we overload the = operator.>p>
Our second stab at the thing class, Header and
implementaiton show the signature for
this overloaded member function is
thing & operator = (const thing &);The code is not particularly difficult. It just creates a separate copy of the dynamic array (_bucket), so that the host member (the instance on the left side of the operator) is a complete replica of the argument (the thing on the right side of the operator). The only tricky thing we do is make sure that we check for a statement of the form X = X.
The same problem occurs when a function receives a value parameter (call by value). C++ will,
unless we do something about it, make a bit-by-bit copy of the actual parameter. This
is fine for numeric or pointer arguments, but for class instances, a shallow copy of the
parameter will leave the function able to manipulate the deep structures of the actual
parameter. This can be quite problematic, but there is a (relatively) easy solution to
the problem: the copy constructor. It is an overloaded constructor with form
thing (const thing &)Note that the constructor (as with the overloaded = operator) takes a const reference to a class instance, and like the overloaded assignment, it makes a copy of dynamic memory.
int& operator [] (const thing &);(I suppose I put this here to show a number of functions that use a const thing reference as an argument!) The code is
// safe array subscripting // overloaded operator [] int& thing::operator[] (int x) { if (x < 0 || x >_count) { cerr << "out of range index\n"; exit(1); } return (_bucket[x]); }We note that the [] operator (isn't that an odd way to think of array indexing? as an operator? Well, why not??) checks its argument, an array index. If the index is out of range, then we just terminate gracefully. This prevents us from having an array index run amok, which is a very difficult debugging problem.