i have an int variable in a class derived from CDialog, and i need its value in another dialog class. Aside from declaring it static is there a way to access this variable?
Assuming there is a common parent that both dialog boxes share, you could declare the variable in the parent, then pass a *pointer to the variable to each dialog box. Then, if it's updated in one dialog, the parent and the other dialog will have access to the updated value through the pointer.
...
I just want to mention that passing pointer to the class variable from outside is a very dangerous style of work because if somebody will delete it in one place you will never be able to know that in all the other classes...
maybe you can put this common variable as member to your devived from CWinApp class, and declare get and set methodes for this variable...
Issahar Gourfinkel
senior software engineer
Israel
Hi guys! I'm a C++/MFC newbie and I was curious why nobody recommended accessor functions to solve this problem. I can see how exposing a pointer to a member variable could compromise the class's integrity in the same way a public member would, but it seems to me adding the variable to the CMyApp class would effectively be the same as using a global variable (a four letter word according to some).
Are there pitfalls to using accessor functions that we should know about? Are there reasons not to use them, like in this example?
Thanks a lot!
~Mike
Any man willing to sacrifice liberty for security deserves neither liberty nor security.
Most of the time, I go out of my way to use Get() and Set() functions to access member variables (especially of other classes), rather than access the variable itself.
But, modal dialogs are an exception (to me). User interface applications generally are single threaded and complete program control is passed to the dialog until it is completely finished. So, especially in the past, I would pass pointers in to modal dialogs. It's not all that dangerous. I just checked whether they are NULL before using them.
However, instead of passing pointers to variables, I now normally pass a pointer to the parent window, through which I can access the Get() and Set() functions of the variable. You're always sure that the parent window is going to be there with modal dialogs (unless something very catastrophic happened -- then you've got bigger problems).
But, to clarify... the part I think is good programming practice is to be in the habit of using Get() and Set() functions, rather than accessing the variable by it's pointer. I don't like the idea of making variables global to the application though, only to the parent of the dialogs that need to share it.
I try to do the safe thing, but I'm not a purist. I guess they call that "pragmatic"?
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.