So I've been messing around with C++ trying to improve my knowledge and came across a project idea that I like, here is a sort of rough description of what I am trying to achieve.
I have a polymorphic setting where I have a base class of type Menu the interface of which is:
class Menu
{
protected:
std::vector<std::string> elements;
public:
friend void printMenu(Menu &);
virtual void Commands(int);
};
and derived classes of type AMenu, BMenu...etc, bodies of whom look something like this:
class MainMenu : public Menu
{
public:
MainMenu();
void Commands(int);
};
Menu::Menu()
{
elements = {"el1","el2"...};
}
Commands takes an int and has a switch statement to execute functions for each Menu called by printMenu()
rough implementation of printMenu()
void printMenu(Menu &M)
{
//code
int counter = 1;
for (auto x : M.elements)
std::cout << '(' << counter++ << ')' << ' ' << x << '\n';
//get user input
M.Commands(option);
}
now I'd like it that if the user inputs say -1 the previous menu would be displayed to them
something like AMenu --> BMenu --> CMenu --> BMen -- > AMenu
I've basically hit a wall trying, here's what I've tried thus far:
-- I tried creating a global std::stack
where every time a menu is printed to the screen an object of that type gets stored in the stack, and if the user inputs -1 the object is thus popped
-- Instead of the std::stack
being global I've put it in Base as static
static std::stack<Menu> S;
and every time an object of type Menu is printed I push it to S and when the user enters -1 I pop S and printMenu(S.top());
and a couple other desperate attempts all of which failed to give me the result I desire, instead what I got was when the user inputs -1 it sends them to the previous menu but then when they try to access another option from the menu, the app just shuts down!
I'd like to know if the way I went is even remotely viable and if it is not please point me to the correct way.
I've got a solid understanding of basic C++ and just came off my Intro to OOP course in uni, also got basic knowledge of STL containers and data structures.