Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a pointer to a function pointer?

I'm trying to create a struct that have 2 function, which may be rewritten if needed later. The functions are: onClicked() and onClickedRight(). The code for the struct:

typedef struct {
    QString text;
    QString infoText;
    QUrl iconSrc;
    QColor iconColor;
    void (*onClicked)() = nullptr;
    void (*(*onClickedRight))() = &onClicked; // by default, execute the same function from onClicked()
} ConfigButton;

How I'm trying to execute these functions:

ConfigButton b;
...
// test if click funtion has been defined, to execute it
if (b.onClicked)
    b.onClicked(); // this one work just fine

...

if (*(b.onClickedRight))
    (*(b.onClickedRight))(); // this one crashed

Is it even possible? Am I missing something?

like image 469
Rafael Vissotto - Inel Avatar asked Jan 29 '20 19:01

Rafael Vissotto - Inel


People also ask

Can you have a pointer to a function?

You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.

How do you initialize a pointer to a function in C++?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator ( & ). The address-of operator ( & ) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number .

Which of the following is a pointer pointing to function?

Syntax of function pointer In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an integer value as an argument.


1 Answers

When onClicked is a function, both &onClicked and onClicked evaluate to the same thing -- a pointer to the function.

If you want to create a pointer to a function pointer, you need a pointer to a function as a variable first.

However, given your usage, you need just a pointer to a function.

typedef struct {
    QString text;
    QString infoText;
    QUrl iconSrc;
    QColor iconColor;
    void (*onClicked)() = nullptr;
    void (*onClickedRight)() = onClicked;
} ConfigButton;

and

if ( b.onClickedRight)
    b.onClickedRight();
like image 115
R Sahu Avatar answered Oct 05 '22 13:10

R Sahu