Bag ADT using Dynamic Array – 4
February 13, 2011 Leave a comment
We now look at the implementations of the overloaded += and + operators.
7. void operator += (const Bag& addend);
The Items in the addend are added to the data array of the calling Bag instance. In case, the data array does not have enough capacity, we call the resize function.
void Bag :: operator += (const Bag& addend)
if ( used + addend.used > capacity)
resize (used + addend.used);
for (size_t i = 0; i < addend.used; i++)
data[used+i] = addend.data[i];
used + = addend.used;
It is a good habit to check for boundary cases such as the call: b + = b;
8. The overloaded + operator. : Bag operator + (const Bag& b1, const Bag& b2);
implementing this is simple if we use the overloaded += operator, which is what we will be doing.
Bag Bag::operator + (const Bag& b1, const Bag& b2)
Bag union ( b1.capacity + b2.capacity);
//note that since this is a friend function, we can access the private variable, capacity.
union + = b1;
union + = b2;