I’m a new programmer trying to teach myself C++ and OOP. Right now I’m working on a project with multiple states, and it’s my first attempt at a bigger programming task/challenge. Right now I’m trying to work on a simple menu state class, but I’m not sure how to go about designing it to do what I want. Specifically, I’m a beginner programmer, and I’m not sure what data types or templates to use.
Here’s a brief description of the type of menu screen that I want to make:
I’m trying to make a simple menu screen that has multiple ‘menu elements’ listed. Each ‘menu element’ contains a string (which is used to display the name of the element or item) and a function (to change states, screens, do a task, etc.). — The other ‘feature’ of the menu system that I want to have is the ability for selection to wrap around. For example, if the menu has 3 items, I want the user to be able to press up and down to switch the currently selected element, and if the user is on the last element (#3) and presses down again, they wrap back around to element #1. (and vice versa..)
Now, I ~think~ that this will require me to make a new class called ‘MenuElement’, and a class called ‘MenuState’ which contains and allows the user to switch between and select a specific element.
As a new, self-taught C++ programmer, I have limited experience with some of the more advanced containers and I’m much more familiar with simple c-style arrays. I have a little bit of experience with vectors, and I know a little bit about linked lists, maps, and trees, but I’m not sure which container type to use for this situation. I’ve seen examples of using pointers to create a circular linked list before, but the example was in C and it seemed a little bit clumsy. Is there a specific type of contain that bests fits my problem? Or am I over-thinking it, and I should just pick one and run with it?
I think I could eventually get this system up and running using an array of MenuElements with a series of conditional statements. However, I’m really interested in actually learning how to improve my programming and design, not only so that my code runs faster, but also so that my code is clean and logically constructed.
Wrap-around can be done with modulo arithmetic, i.e. given a private member index variable named
idx_of the active cursor into the array of menu elements, you could do have a member functionspage_down()andpage_up()like thiswhere
num_elements()is the size of the current menu.For your general design question, a sketch of your class hierarchy would use the Composite Design Pattern (Wikipedia). This defines an abstract menu interface called
IMenuand derives bothCompositeMenuand aLeafMenuas concrete classes. This allows arbitrary levels of nested submenus.Note that since
num_elements()is a member function that allows for dynamic updates on the subMenus (i.e. it would allow drag-and-drop of menu items).