Global Objects

Are global objects constructed in a program before everything else?

For example this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

using namespace std;

int main()
{
	cout<<"What year was Israel founded in?"<<endl;
	cout<<"(A)1948, (B)1949, (C)1950, (D)1921"<<endl;

	cin>>answer;

	if (answer == 1)
	{
		correct = true;
	}

	if (answer != 1)
	{
		correct = false;
	}


	if (correct == true)
	{
		cout<<"Congratulations"<<endl;
	}

	if (correct == false)
	{
		cout<<"You fail"<<endl;
	}

return 0;
}

int answer;
bool correct;


Shouldn't it compile? My IDE doesnt put red lines under it but my compiler gives errors. I saw some posts earlier saying that a global object is constructed before everything else.

Can anyone enlighten me?
When an object is constructed and where it is visible are orthogonal things. Declare or define variables where they are visible to the code that uses them. (Which means either declare them or define them before main for this case.)
Well then that brings me to this question:

In this sample MFC code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Ex11_02.cpp  An elementary MFC program
#include <afxwin.h>                        // For the class library
     
// Application class definition
class COurApp:public CWinApp
{
   public:
      virtual BOOL InitInstance() override;
};
     
// Window class definition
class COurWnd:public CFrameWnd
{
   public:
      // Constructor
      COurWnd()
      {
         Create(NULL, _T("Our Dumb MFC Application"));
      }
};
     
// Function to create an instance of the main application window
BOOL COurApp::InitInstance(void)
{
   m_pMainWnd = new COurWnd;               // Construct a window object...
   m_pMainWnd->ShowWindow(m_nCmdShow);     // ...and display it
   return TRUE;
}
     
// Application object definition at global scope
COurApp AnApplication;                     // Define an application object 


How is the winmain function added? Since it cant magically be added when you make the COurApp it must have been included in the include statement at the starting. Well then how does it know that COurApp exists if it is defined underneath it?
Last edited on
Can you point to the line(s) you are questioning?
The COurApp and its member function prototype have been placed above everything else, so everything else should know about it.
Look up "forward declare", it works for variables, functions, classes, etc.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

extern int x;
int f();

int main()
{
    std::cout << x   << std::endl
              << f() << std::endl;
}

int x = 7;
int f()
{
    return 4;
}
Last edited on
Never find thanks!
It's ok if you don't find any thanks, I don't need it ;)
Last edited on
Woops lol, I meant

never mind, but thanks!
Topic archived. No new replies allowed.