Bag ADT: Abstract Data Types in C++ – 4

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

———

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: