PDA

View Full Version : Pointers to Member Functions


Doug Broadwell
13th May 2007, 19:33
I have a table where one of the items is a pointer to member function, e.g.:

class State : public QObject {
QOBJECT
public:
State() {}
~State() {}
int Set_State (uint Object, int New_State);
int Validate_State(int New_State);
};

typedef int (State::* pState_Valid)(int Requested_State);

struct {
int Current_State;
pState_Valid pValidator;
} State_Tbl[] = {
0, &State::Validate_State,
1, &State::Validate_State
};

int State::Validate_State(int Requested_State) {
int Validated_State;
...
return(Validated_State);
}

int State::Set_State(uint Object, int Requested_State) {
int Validated_State;

Validated_State = (*State_Tbl[Object].pValidate_State)(Requested_State);
...
return(Validated_State);
}

The error I get (gnu compiler) on the line that's calling the member function is:

error: invalid use of 'unary*' on pointer to member

What am I doing wrong?

Thanks,
Doug Broadwell

marcel
13th May 2007, 19:40
Use this instead:
Validated_State = (State_Tbl[Object].*pValidate_State)(Requested_State);

You were not dereferencing the function, but the struct object.
Try dereferencing the function pointer, which is the correct way.

Regards

Doug Broadwell
14th May 2007, 02:57
Thanks Marcel, that fixed that error. Now I'm getting the error:

'pValidator' undeclared (first use this function)

?????
Help again.

high_flyer
14th May 2007, 10:53
on which line in the code this error comes?

Doug Broadwell
14th May 2007, 18:07
The error is on this line:

Validated_State = (*State_Tbl[Object].pValidate_State)(Requested_State);

Doug

high_flyer
14th May 2007, 18:14
The error is on this line:

Validated_State = (*State_Tbl[Object].pValidate_State)(Requested_State);

Doug

But that is the same code you had before when you started the thread...:confused:

marcel
14th May 2007, 18:55
Validated_State = (State_Tbl[Object].*pValidate_State)(Requested_State);

Who is pValidate_State?
You should call (State_Tbl[Object].*pValidator)(Requested_State);, because pValidator points to State::Validate_State.

What is the point of pointers to functions if you will call the functions directly?

Doug Broadwell
15th May 2007, 19:47
Oops, you're right, the actual line that is generating the error is the edited one:

Validated_State = (State_Tbl[Object].*pValidator)(Requested_State);

My mistake in copying/simplifying the code and having 'pValidate_State' instead of the correct 'pValidator' here. It still gets the 'pValidator undeclared' error.

Doug

Doug Broadwell
16th May 2007, 00:08
Just realized one problem, I haven't instantiated any State objects yet to point to!

My newbe status reveals itself yet again.

Doug