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

We continue our discussion of the Bag ADT.

We first look at the implementation of the insert function.

(All function implementations are part of an implementation file, bag.cpp, in which, among other header files, “bag.h” is included.)


The insert function : bool insert (const Item& myItem); works as follows:

– it inserts the argument, myItem into the “data” array if there is space for insertion into the array, i.e. if size( ) < CAPACITY.

– In that case, it inserts myItem at index “used” in the array, and returns true.

– Otherwise, (i.e. if there is no space for insertion) it returns false.


bool  Bag :: insert ( const Item& myItem)


if ( size ( ) >= CAPACITY)

return false;

data[used] = myItem;

used ++;

return true;



Note that we pass the argument myItem by reference. Passing by reference helps to optimize on memory in case the argument is of a large size. Further, by passing it as a const reference, we ensure that what we are passing does not get accidentally modified.


Leave a Reply

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

You are commenting using your 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: