Question

In the project, I created the main.cpp and main.h, and define public variables int a, and int b in the .cpp file.

Currently I create a class Aproc in aproc.cpp and aproc.h (It is none dialog), and add into main.cpp by using include aproc.h.

For now, in aproc.cpp I want to get the variable "a" which is defined in main.h, I am using this code:

((MainDlg*)GetParent())->a;

to compiler it works well, but it will run time error in GetParent,

variable is declared as

public:
    int a;

aproc.h is delcared as

class aproc.h : pulbic CWnd
{

}

How do I get the public variable ?

Was it helpful?

Solution

You have not told us if the aproc window is a child of main, and if the aproc window has been created, and what run time error you get. To avoid these possible problems you can use the global MFC function AfxGetMainWnd().

((CMainDlg*)AfxGetMainWnd())->a

OTHER TIPS

If your program crashes on ((MainDlg*)GetParent())->a;, it most likely means GetParent() returned NULL, indicating failure. Check for return values before using the result of GetParent().

MainDlg *p = (MainDlg *)GetParent();
if(p == NULL) {
    int err = GetLastError(); // <--- inspect this return value, it'll tell you why it failed
}

GetParent() usually fails for one of the following reasons:

  • Window wasn't created yet, either by directly or indirectly calling Create()
  • The window is a top-level window that is unowned or does not have the WS_POPUP style
  • The owner window has WS_POPUP style.

Since you seems to be working with dialogs(your cast to MainDlg), I suspect #1 applies and you're calling GetParent() prior to dialog creation/OnInitDialog.

GetLastError()

GetParent()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top