In MFC why do I need to create a global instance of CWinApp?
c++, mfc, user-interface, windows
Solution
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.
Problem
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?