Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 383
  • 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.

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

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