Function that returns a function pointer?

I'm trying to make a console-based UI based on a menu system. I want 'Menu' and 'MenuOption' to be classes in themselves, with Menu holding an array of MenuOptions.
In MenuOption I want two global variables: one which holds the MenuOption "text", and one that is a function pointer for the function that option actually refers to. Therefore, i need a 'get' method to return the function pointer. I've looked at a few tutorials but they don't seem to be working for me: they don't explain how to incorporate separate .h and .cpp files. Code for MenuOption.h and MenuOption.cpp are below.

MenuOption.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef MENUOPTION_H
#define    MENUOPTION_H

class MenuOption
{
    private:
        std::string text;
        void (*function)();
    public:
        MenuOption(std::string optionText, void (*optionFunction)());
        std::string getText();
        void (*getFunction())();
        virtual ~MenuOption();
};

#endif    /* MENUOPTION_H */ 


MenuOption.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include "MenuOption.h"

using namespace std;

MenuOption::MenuOption(string optionText, void (*optionFunction)()) : text(optionText), function(optionFunction)
{
}

string MenuOption::getText()
{
    return text;
}

void MenuOption::(*getFunction())()
{
    return (*function)();
}

MenuOption::~MenuOption()
{
}


I'm sure that "getFunction()" function is stupidly wrong, but I've no idea of how to do it properly. Could anyone give some assistance? :)
With getFunction(), I suppose you do not want to execute the function, just return the function pointer.

If that's the case, focus on:

1. The return value on Line 15
2. What you are doing on Line 17 - are you returning the value of function or invoking the address pointed to by function?
What you want is for MenuOption::getFunction to return a function pointer.
You have a few of problems.

1) The function is declared as returning nothing (void), where you want it to return a function pointer.
2) You're declaring getFunction as accepting a function pointer as an argument.
3) Your return statement executies the function, rather than returning the pointer.

1
2
3
void (*)() MenuOption::getFunction()
{  return this->function;
}

And of course, your declaration must match.

BTW, text and function are not global variables. They are member variables.
Topic archived. No new replies allowed.