4. Examine the following declarations and definitions for a dynamic array-based
ID: 3801829 • Letter: 4
Question
4. Examine the following declarations and definitions for a dynamic array-based implementation for the
ADT Stack, and do problems (1) to (4).
______________________________________________________________
const int MAX_STACK = 128;
typedef char Type;
class Stack
{
public:
Stack(int numElements = MAX_STACK);
Stack(const Stack& original); //copy constructor
~Stack(); //destructor
const Stack & operator=(const Stack & rStk); // assignment operator
void push(Type item);
void pop(Type & Item);
private:
int myTop;
int myCapacity;
Type* myArray;
}
void Stack::Stack(int numElements)
{
myCapacity = numElements;
myArray = new Type[myCapacity];
myTop = -1;
}
_________________________________________________________________
(1) Write the implementation of the destructor:
(2) Write the implementation of the assignment operator:
(3) Write the implementation of the pop method.
Explanation / Answer
const int MAX_STACK = 128;
typedef char Type;
class Stack
{
public:
Stack(int numElements = MAX_STACK);
Stack(const Stack& original); //copy constructor
~Stack(); //destructor
const Stack & operator=(const Stack & rStk); // assignment operator
void push(Type item);
void pop(Type & Item);
private:
int myTop;
int myCapacity;
Type* myArray;
}
// constructor
Stack::Stack(int numElements)
{
myCapacity = numElements;
myArray = new Type[myCapacity];
myTop = -1;
}
(1) Write the implementation of the destructor:
Stack::~Stack(){
delete [] myArray; // deleting dynamically allocated memory
}
// To write this function, We need the information about the value of myTop, myCapacity of 'rStk'.
But here there is no function in Stack class that gives the information about these value
(2) Write the implementation of the assignment operator:
const Stack& Stack::operator=(const Stack & rStk){
// deleting current content
delete [] myArray;
// allocating memory based on rStk content
}
(3) Write the implementation of the pop method.
void Stack::pop(Type & Item){
if(myTop < myCapacity){
Item = myArray[myTop]; // storing top element in Item parameter
myTop = myTop - 1; // deleting top elememt
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.