Bag ADT using Dynamic Array – 4

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);

//copy Items.

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;

return union;

}

———

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: