Is it correct, following object orientation, to use pointers for C ++ functions?

5

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?

    
asked by anonymous 15.10.2016 / 04:35

1 answer

4

Correct can only be said by seeing a concrete case. In this respect the question can not be answered. The concrete case was not placed, so even if I say I can do it, if I do it wrong, it's no use whatsoever.

This has nothing to do with object orientation. Even if it had, what matters is solving the problem well not meeting what the paradigm says.

Pointers to functions are perfectly valid in many situations.

Of course in C ++ it's more common to use functors or most recently lambdas . You can also make creative uses of templates or the simple < a href="https://en.wikipedia.org/wiki/Virtual_function"> polymorphism . If you consider that you need this indirection the ideal is to use a more idiomatic mechanism of C ++ and more modern (because it has advantages).

    
15.10.2016 / 04:56