I have a structure called mystruct, into which I would like to place a function pointer called pf, which points to a function that takes a float as input, and produces a float as output. I would then like to have a constructor which takes a function pointer as input, and defines pf as a pointer to that function. Here is what I have so far
1 2 3 4 5 6 7 8
struct mystruct {
mystruct(float(*)(float));
float (*pf)(float&, unsigned);
};
mystruct::mystruct(float(*pf)(float)) {
this->pf = pf; // set the input equal to pf in the structure
}
This doesn't work, due to my relative lack of understanding of function pointers. However, having read about the basics of function pointers I am quite confused as to how to make this work. I'd really appreciate a fix!
All you need to know about function pointers is that the function pointer points to the starting address of the routine given to it. The function pointer can then invoke (call) the function it points to.
Now onto your question. First of, the function pointer declaration within the constructor's parameter list doesn't match the parameter list of pf. The two need to be consistent. I would personally refer to a function rather than point to one (I'm referring to the function pointer within the constructor's parameter list). Such code may look like this:
Is that right? My compiler seems to like it but I haven't had a chance to test it. I find the way C++ notates function pointers really confusing... I'm sure that for those that understand everything surrounding it the notation probably makes a lot of sense, but as someone who's used to the "type then name" way of things in C++ I'm struggling a little, I'm sure I'll get a hang of it eventually...
They do something else (the first is "the object itself", the second is a copy of the object), but in terms of notation inside the function, they are the same: you're using an object, not an address.
Example:
1 2 3 4 5 6 7
void incrementV(int a) { ++a; }
void incrementR(int &b) { ++b; }
int main () {
int c(5), d(7);
incrementV(a);
incrementR(d);
}
As you can see: the code inside the function body, as well as in the calling code, is the exact same. The difference is that the first function does nothing (a is copied, incremented, then destroyed; the original object c remains untouched), while the second does what you expect (b is an alias of d, b is incremented which also increments d, b is destroyed but d's value is still incremented).
I thought so, too, but according to GCC, both pf = &r_routine and pf = r_routine are equivalent. Neither make a difference. Of course, Microsoft's compiler might cry like a little girl when it encounters the assignment, but GCC doesn't. Referring to a routine isn't the same as referring to a variable (in my opinion) because a routine is a collection of consecutive statements; a variable is not.
ausairman wrote:
"Second, how would I call this function now?" (sic)