Bag ADT using Dynamic Array – 2

We now look at the implementation of functions from the Bag ADT.

We start with the 2 constructors and the overloaded assignment operator.

1. Constructor:It allocates dynamic memory which is given by the argument passed to it. (And in case, no argument is passed to it, DEFAULT_CAP is used as the default argument.)

Bag :: Bag (size_t initial_cap)

{

data = new Item [initial_cap];

capacity = initial_cap;

used = 0;

}

——

That was simple enough. We now go to the copy constructor.

2. Copy constructor: Bag (const Bag& other_bag);

Note that a copy constructor is required for our Bag ADT since we are using dynamic memory in our class. If we do not provide a copy constructor, the default copy constructor would be used which, since it does a shallow copy, would result in undesired outcomes. For the same reason, we also need to overload the assignment operator, which we shall see a bit later.

—–

Bag :: Bag ( const Bag& other_bag)

{

//allocate memory equal to other_bag.capacity number of Items.

data = new Item[other_bag.capacity];

//set capacity value.

capacity = other_bag.capacity;

//set “used” value.

used = other_bag.used;

//copy Items.

for (size_t i =0; i< used; i++)

data[i] = other_bag.data[i];

}

——–

3. We now come to the overloaded assignment operator.The implementation is fairly along the same lines as the copy constructor, with the exception that we first check whether the calling bag instance’s capacity is equal to other_bag’s capacity.

Note that the Bag instance calling the assignment operator has already been instantiated. Hence, this is slightly different from the scenario of calling a copy constructor.

——–

void Bag::operator = (const Bag& other_bag)

{

if (capacity != other_bag.capacity)

{

//allocate new memory.

Item *new_data = new Item[other_bag.capacity];//new_handler gets called in case //of failure of memory allocation.

delete [ ] data;

data = new_data;

capacity = other_bag.capacity;

}

for (size_t i = 0; i < other_bag.used; i++)

data[i] = other_bag.data[i];

used = other_bag.used;

}

———

We make a note here: we wrote “new_data = new Item [..]; delete [ ] data; data = new_data;” instead of the more direct, “delete  [ ] data; data = new Item [..];”

The reason is that it is a good habit to maintain the invariant of the ADT at any time when “new” is called, because otherwise, a failure of the “new” call would lead to problems in debugging.

——–

In the next post, we shall look at implementing other functions of the Bag ADT.

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: