Bag ADT: Abstract Data Types in C++ – 4
February 13, 2011 Leave a comment
We now look at the overloaded += member function.
void operator += ( const Bag& addend);
We note the following:
– the operation can only take place if the total size of the 2 bag instance (the calling bag instance and addend) is no greater than CAPACITY.
– If enough space is available, we simply copy the contents the addend’s data array into the calling instance’s data array.
void Bag :: operator += ( const Bag& addend)
assert ( size ( ) + addend.size ( ) < = CAPACITY); // include assert.h for this.
addend_size = addend.size ( );
for (int i = 0; i < addend_size; i++ )
data[used + i ] = addend.data[i];
Note that we use “i < addend_size” as the condition in the for loop, instead of the more natural, “i < addend.size ( )”. This is because the latter condition would fail in case the addend instance is the same as the calling instance (i.e. something of the kind, b + = b.)