C++ •Create a Stack class to perform ‘push’ and ‘pop’ operations. For the purpos
ID: 3825239 • Letter: C
Question
C++
•Create a Stack class to perform ‘push’ and ‘pop’ operations. For the purpose of this exercise, make the capacity to be 3
•Create a PushToFullStackException class, and a method called ‘what’ to return an overflow exception message. Provide code to throw and handle such an exception in this class.
• Create a PopEmptyStackException class, and a method called ‘what’ to return an underflow exception message. Provide code to throw and handle such an exception in this class.
•Use this test code
Stack myStk; //Capacity of 3
cout << "Popping right away.";
myStk.pop();
cout << " Pushing 1st item.";
myStk.push(1);
cout << " Pushing 2nd item.";
myStk.push(2);
cout << " Pushing 3rd item.";
myStk.push(3);
cout << " Pushing 4st item.";
Popping right away EXCEPTION: Your stack is empty Pushing 1st item Pushing 3rd item Pushing 4st item XCEPTION: Your stack is fullExplanation / Answer
#include <iostream>
using namespace std;
class PushToFullStackException
{
public:
PushToFullStackException()
{
message = "EXCEPTION: Your stack is full!";
}
PushToFullStackException(string msg)
{
message = msg;
}
string what()
{
return message;
}
private:
string message;
};
class PopEmptyStackException
{
public:
PopEmptyStackException()
{
message = "EXCEPTION: Your stack is empty!";
}
PopEmptyStackException(string msg)
{
message = msg;
}
string what()
{
return message;
}
private:
string message;
};
class Stack
{
int array[3];
int top;
public:
Stack()
{
top = -1;
}
void push(int value)
{
try
{
if(top == 3)
throw PushToFullStackException("EXCEPTION: Your stack is full!");
top++;
array[top] = value;
}
catch (PushToFullStackException& me)
{
std::cerr << me.what();
}
}
int pop()
{
try
{
if(top == -1)
throw PopEmptyStackException("EXCEPTION: Your stack is empty!");
top--;
return array[top+1];
}
catch (PopEmptyStackException& me)
{
std::cerr << me.what();
}
return -1;
}
};
int main()
{
Stack myStk; //Capacity of 3
cout << "Popping right away.";
myStk.pop();
cout << " Pushing 1st item.";
myStk.push(1);
cout << " Pushing 2nd item.";
myStk.push(2);
cout << " Pushing 3rd item.";
myStk.push(3);
cout << " Pushing 4st item.";
myStk.push(4);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.