Skip to content

Instantly share code, notes, and snippets.

@bcrist

bcrist/pushpop.cpp

Created Apr 12, 2014
Embed
What would you like to do?
Menu Stack
#include <stack>
#include <memory>
#include <cassert>
// Polymorphic base class for menus
class Menu
{
public:
// Common to all menus:
// (for example)
virtual void draw() = 0;
virtual void onMouseMove(int x, int y) = 0;
virtual void onMouseButton(int button, bool is_down) = 0;
// ... etc.
}
// A concrete menu class representing the main menu:
class MainMenu : public Menu
{
public:
MainMenu() {}
virtual void draw() { /* ... */ }
virtual void onMouseMove(int x, int y){ /* ... */ }
virtual void onMouseButton(int button, bool is_down) { /* ... */ }
// ...
}
// Of couse, normally you will have other menus as well.
int main(int argc, char** argv)
{
// std::stack is an adapter container that uses std::deque by default.
// You could just as easily use std::deque, std::vector, or std::list directly
// if you change push() to push_back(), top() to back(), and pop() to pop_back().
std::stack<std::unique_ptr<Menu>> menus;
Menu* m = new MainMenu();
menus.push(std::unique_ptr<Menu>(m));
assert(menus.top().get() == m);
menus.pop(); // the object pointed to by `m` is destroyed when the std::unique_ptr in the stack is removed.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment