Improve company productivity with a Business Account.Sign Up

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 387
  • Last Modified:

MFC global Variables

I've created an SDI application which uses a dialog as the logon screen
. I have another screen which allows the user to change their password.
Is it possible to create a global variable that you can access anywhere within
your program.  I want to store the password the user used to log in
and then display it when they open the changepassword screen. Any help would
be appreciated thanks.
1 Solution
declare the variable as public in your C*App class
CString Password;

you can then access it it other classes by declaring it as an extern variable
extern CString Password.

You can add a static member variable to your CWinApp derived class.

// myapp.h
class CMyApp : public CWinApp
    static CString strPswd;

// myapp.cpp
static CString CMyApp::strPswd = _T("");

// any.cpp
#include "myapp.h"

CMyApp::strPswd = _T("abc");
Yes, you could declare global variable in your .cpp file, but is has its advantages and disadvantages. Advantage is that it could be accessed by any function, and disadvantage is that it might be hard for you to debug your application if you use this variable in too many instances. To be honest with you I never declare global variables, instead I rather design my functions so that I can pass and return variables (values). Why don't you declare that variable as public: in your .h file, rather than having it declared global.
And one more thing - people say global variables in c/c++ don't go along with the spirit of structured and OO programming :) .

Good Luck!
Hi !!
  No need of global variable. Declare right in u r application class. U can access it anywhere using AfxGetApp()->m_MyVariable. where m_MyVariable is decalred in app class.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now