I'm creating classes that represent items in a menu, each item executes an action and I'm assigning the action by a function pointer to each instanced menu item, is this valid following POO? or is there an easier and more practical way to do it?
Follow the code below:
class MenuItem{
public:
MenuItem(GLsizei x, GLsizei y, string texto, bool enabled = false);
~MenuItem();
void display();
void setAction(void (*action)());
void runAction();
private:
GLsizei x, y;
string texto;
bool enabled;
void (*action)();
};
void MenuItem::setAction(void (*action)())
{
this->action=action;
}
void MenuItem::runAction()
{
action();
}
Class that instantiates MenuItem:
class Menu{
public:
Menu(vector<string> itens, GLsizei width, GLsizei heigth);
~Menu();
void selectNext();
void selectPrevious();
MenuItem* getSelectedItem() const;
void display();
private:
MenuItem **itens;
int selectedItem;
int contItens;
GLsizei width, heigth;
};
void function(void){
cout<<"faz alguma coisa"<<endl;
}
Menu::Menu(vector<string> itens, GLsizei width, GLsizei heigth)
:width(width), heigth(heigth)
{
contItens=0;
this->itens=new MenuItem*[itens.size()];
for(string s: itens){
this->itens[contItens++]=new MenuItem(width/2, heigth/2-contItens*30, s);
}
this->itens[selectedItem=0]->setEnabled(true);
this->itens[0]->setAction(function);//aqui eu coloco a ação no primeiro item
}
calling function:
void keyboard(unsigned char key, int x, int y){
if(key=='s')
menu->getSelectedItem()->runAction();
if(key=='d')
menu->selectNext();
if(key=='a')
menu->selectPrevious();
glutPostRedisplay();
}
I just created function
for testing. My idea is to put a method in Menu
that places through the function pointer the action referenced to each item. But the code itself works, I'm just in doubt if it follows OOP and if it is not so complex?