I know there are tons of stuff out there explaining linked lists and stuff but I wrote this one off the top of my head and just to make sure I understand them I did not want to compare to a working one, rather get some input.
Mainly want to make sure this code:
1) Has no memory leaks
2) Follows proper programming practices/industry standards
3) Not doing anything unnecessary
Header:
#pragma once
#include <string>
struct MenuItem {
std::string menuText;
int xPos;
int yPos;
MenuItem* next;
static MenuItem* head;
};
class Menu {
private:
MenuItem* m_pMenuItems;
public:
Menu();
~Menu();
void addMenuItem(std::string menuText, int xPos, int yPos);
};
Source:
#include "Menu.h"
MenuItem* MenuItem::head = 0;
Menu::Menu() {
m_pMenuItems = NULL;
}
Menu::~Menu() {
// clean up the linked list
MenuItem* temp;
temp = m_pMenuItems->head;
while(temp) {
m_pMenuItems = temp->next;
delete temp;
temp = m_pMenuItems;
}
}
void Menu::addMenuItem(std::string menuText, int xPos, int yPos) {
// check and make sure we have a menu item
if(m_pMenuItems) {
// if it does exist we just need to create a new MenuItem and set it to the head
MenuItem* temp;
// create a new MenuItem
temp = new MenuItem();
temp->menuText = menuText;
temp->xPos = xPos;
temp->yPos = yPos;
// set the next to the current head and then reset the head to the last created
temp->next = m_pMenuItems->head;
m_pMenuItems->head = temp;
} else {
// otherwise we need to create a menu
m_pMenuItems = new MenuItem();
// assign the values
m_pMenuItems->menuText = menuText;
m_pMenuItems->xPos = xPos;
m_pMenuItems->yPos = yPos;
// set the head to itself since it is the only one
m_pMenuItems->head = m_pMenuItems;
}
}