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?
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.
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 .
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With