Search code examples
visual-c++mfc

Can I prevent the need to pass this into inherited function as a parameter?


Base class 1:

class CBaseEditor
{
public:
    bool CBaseEditor::ImportTemplate(CWnd* pParent)
    {
        CFileDialog dlgImport(TRUE,
        _T(".XSL"), _T(""), 
        OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, 
        _T("FilterText"), pParent);
   }
}

Base class 2:

class CResizingDialog : public CDialogEx
{

}

Dialog class, derived from both bases:

class CFieldServiceGroupReportDlg : public CResizingDialog, public CBaseEditor
{
    private:
    void SuneFunc()
    {
        ImportTemplate(this);
    }
}

My ImportTemplate function, is there anyway for it to get access to the "this" from the caller without having to pass "this" in?


Based on the comment provided I have come to the conclusion that the best thing to do is change my existing constructor (field class has since been renamed):

CPublishersDatabaseViewerDlg::CPublishersDatabaseViewerDlg(CWnd* pParent /*=nullptr*/)
    : CResizingDialog(L"GroupsReport", IDD_DIALOG_PUBLISHERS_DATABASE_VIEWER, pParent)
    , m_strPreviewXSL(L"")
{
    m_strPreviewXSL = theApp.GetStringSetting(L"Options", L"PublisherDB_Style", L"PublisherDB--Field Service Groups");

}

By design the dialog class accepts a parent. Likewise, I should change CBaseEditor to accept an appropriate parent in some way. Than I won't need to pass it all the time. This is my base constructors:

CResizingDialog::CResizingDialog(const CString& strWindowID, UINT nIDTemplate, CWnd* pParent /* nullptr */, bool bOnlyStorePosition /* false */)
    : CDialogEx(nIDTemplate, pParent)
    , m_bDoNotShowResizeIcon(false)
    , m_bOnlyStorePosition(bOnlyStorePosition)
    , m_bLimitToHorizontalResizing(false)
    , m_strWindowID(strWindowID)
{
    m_rcInit.SetRect(0, 0, 0, 0);
}

CBaseEditor::CBaseEditor() noexcept(false)
{
    Init();
}

Solution

  • Step 1

    Change my dialog constructor to feed in the this to the CBaseEditor:

    CPublishersDatabaseViewerDlg::CPublishersDatabaseViewerDlg(CWnd* pParent /*=nullptr*/) noexcept(false)
        : CResizingDialog(L"GroupsReport", IDD_DIALOG_PUBLISHERS_DATABASE_VIEWER, pParent)
        , CBaseEditor(this)
        , m_strPreviewXSL(L"")
    {
        m_strPreviewXSL = theApp.GetStringSetting(L"Options", L"PublisherDB_Style", L"PublisherDB--Field Service Groups");
    
    }
    

    Step 2

    Add a new CWnd* variable to the base editor and update the constructor:

    CBaseEditor::CBaseEditor(CWnd* pParent /* nullptr */) noexcept(false)
    {
        m_pParentWnd = pParent;
    
        Init();
    }
    

    Step 3

    Change the ImportTemplate function as it no longer needs the parent passed in. We can use the m_pParentWnd instead.