// @topic W10-2-030 IntStack class using dynamic array v2
// @brief class IntStack implementation
#include <iostream>
#include "int_stack.h"
IntStack::IntStack()
: // constructor initializer list
top_of_stack( 0 )
{
allocate_memory( DEFAULT_SIZE );
}//IntStack::IntStack
IntStack::IntStack( IntStack const& another )
: // constructor initializer list
top_of_stack( another.top_of_stack ),
capacity( another.capacity )
{
// 1. allocate exact space for dynamic array of integers
allocate_memory( another.capacity );
// 2. copy existing data elements from another stack over
for ( int idx = 0; idx < another.size(); ++idx ) {
// this = another
memory_block[ idx ] = another.memory_block[ idx ];
}
}//IntStack::IntStack
IntStack& IntStack::operator=( IntStack const& another )
{
if ( this == &another ) {
// beware of self-assngmnt
return *this;
}
top_of_stack = another.top_of_stack;
capacity = another.capacity;
delete [] memory_block;
// 1. allocate exact space for dynamic array of integers
allocate_memory( another.capacity );
// 2. copy existing data elements from another stack over
for ( int idx = 0; idx < another.size(); ++idx ) {
// this = another
memory_block[ idx ] = another.memory_block[ idx ];
}
}//IntStack::operator=
IntStack::~IntStack()
{
delete [] memory_block;
}//IntStack::~IntStack
void IntStack::allocate_memory( int block_size )
{
memory_block = new int[ block_size ];
capacity = block_size;
std::cout << __FUNCTION__ << " capacity = " << block_size << "\n"; //DEBUG
}//IntStack::allocate_memory
void IntStack::reallocate_memory( int block_size )
{
// 1. allocate new memory block
int * ptr_new_block = new int[ block_size ];
// 2. copy existing data elements over to the new block
for ( int idx = 0; idx < size(); ++idx ) {
// new = old
ptr_new_block[ idx ] = memory_block[ idx ];
}
// 3. free old memory block
delete[] memory_block;
// 4. make sure we point to new mem block;
memory_block = ptr_new_block;
capacity = block_size;
std::cout << __FUNCTION__ << " capacity = " << block_size << "\n"; //DEBUG
}//IntStack::reallocate_memory
void IntStack::push( int value )
{
if ( capacity == top_of_stack ) {
// allocate more memory
reallocate_memory( capacity * 2 );
}
memory_block[ top_of_stack ] = value;
++top_of_stack; // stack maintenance
}//IntStack::push
void IntStack::pop()
{
--top_of_stack; // stack maintenance
}//IntStack::pop
int IntStack::top() const
{
return memory_block[ top_of_stack - 1 ];
}//IntStack::top
int IntStack::size() const
{
return top_of_stack;
}//IntStack::size