Home > Back-end >  Why "CWinApp::InitInstance()" called in "MyApp InitInstance()" without error?
Why "CWinApp::InitInstance()" called in "MyApp InitInstance()" without error?

Time:09-27

The InitInstance() in CWinApp is a virtual function, I think it should be reported "undefined reference" error here, But nothing happen. So I want to know why and the reason to put it here. Thanks in advance. Below code is generated automatically by visual studio 2022 for MFC App.

BOOL CSaleSystemApp::InitInstance()
{
    // InitCommonControlsEx() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    // Set this to include all the common control classes you want to use
    // in your application.
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    // login first
    loginDlg = new CMyLoginDialog();
    loginDlg->DoModal();

    CWinApp::InitInstance();  <--- it's a virtual function in CWinApp, why called here?
    ...
}

CodePudding user response:

Correct, CWinApp::InitInstance is a virtual function.

The expression CWinApp::InitInstance(), however, de-virtualizes the function call, delegating it to the implementation provided by CWinApp (or one of its base classes in case CWinApp doesn't implement it [which it does]).

This may seem awkward, but the awkward thing really is, that C ' inheritance model only caters to "true" specialization. It doesn't provide for a way to express "partial specialization", where the derived class and the base class coöperate; it's either the derived class' or base class' virtual function that executes. C doesn't allow you to do "special" things in the derived class in addition to the common things provided by the base1.

<base class>::<virtual function>(...) instructs the compiler to emit a function call to the base class' implementation of virtual function. In case of CWinApp::InitInstance() that function is known to both the compiler and linker, so both the compiler and linker are happy.


1 Though that really is a consequence that we've stopped using classes for what they are meant for. It is ultimately a violation of the Rule of zero.

  • Related