Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MFC why do I need to create a global instance of CWinApp?

Why the constructor of my derived CWinApp should be invoked before main function starts?
Why can't it be something like:

int WinMain()
{
   CMainFrame* pMainFrame = new CMainFrame;
   // etc ...
}

I'm looking for the technical reason that forces this behavior.
Edit:
To make clearer - If I'm using win32 API without MFC the main window is created inside WinMain so what is the difference?

like image 600
Ohad Horesh Avatar asked Oct 08 '22 22:10

Ohad Horesh


1 Answers

Basically, that's because the MFC designers decided to provide the application entry point (WinMain(), not main()) in the library itself, so users would not have to write one.

The application's initialization and termination logic is then relocated to the InitInstance()and ExitInstance() methods of the instance of a user-provided CWinApp-derived singleton. This instance has to exist before WinMain() runs, because it calls the aforementioned methods (and Run() to enter the message loop) and uses it to store state (like the nCmdShow argument it receives).

Defining the CWinApp-derived instance in the global scope is an easy way to ensure it does exist by the time WinMain() runs.

This article has additional details on what happens under the hood when an MFC application starts.

like image 100
Frédéric Hamidi Avatar answered Oct 12 '22 11:10

Frédéric Hamidi