Scope of function pointers

I have declared a function inside my Main.cpp and passed a pointer to the function to an object declared in MenuItem.h. If I call the function from Main it has the desired effect of changing some variables inside Main. If I call the function (via pointer) from an object created from the MenuItem class it does not seem to change the variables.

Main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
int x, y;
void change()
{
x = 10;
y = 10;
}
Main()
{
change();
Obj O(&change);
O.myFunc();
}


Obj.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Obj
{
public:
Obj(void (*func)());
void myFunc();
void (*funcPtr)();
}

Obj::Obj(void (*func)())
{
funcPtr = func;
}

Obj::myFunc()
{
funcPtr();
}


The initial call of change has an effect, but the call from O.myFunc() does not, making me think its an issue of the variables not being in scope of the function call. I have tried searching but cannot find much information regarding this.

Thanks for any help guys,
Odracir123.
I tried your code and it's ok with me with gcc 4.4.
Here x and y are global variables ant then can be accessed anywhere at anytime during the program execution and the code of "change" function stay in the executable during program exectution.

But anyway playing with global variables is evil and in your case there is the solution of functors.
http://www.newty.de/fpt/functor.html

EDIT: fixed typo
Last edited on
closed account (zb0S216C)
It's not a matter of scope, because the compiler would produce an error.

change() sets both x and y to 10 when called. When change() is called, the change takes effect. However, O.myFunc() is set to call change(). When change() is called through O.myFunc(), both x and y would have already been set to 10.

Wazzak
Last edited on
aquaz, I understand global variables should be avoided (and I do avoid them). This specific implementation was just to test the theory of function pointers.

aquaz + Framework, I understand now that it wouldn't be a scope issue. I jumped to that conclusion without really thinking about it. I won't be making that mistake again. The code I presented was a cut down version, next time I'll make sure to use my actual code as it was a completely different issue.

ps. I'll be sure to read the link you posted aquaz. Sorry for the small waste of time, but I did learn something.
Topic archived. No new replies allowed.