Search code examples
visual-c++referencestdvector

Initializing a member std::vector variable of a class that is a reference in c++


The parent class has this variable:

AutoAssignActionVector vAutoAssignActions = dlgSettings.AutoAssignActions();

... where AutoAssignActionVector is: using AutoAssignActionVector = std::vector<S_MWB_AUTO_ASSIGN_ACTION>;.

Now, I want to pass this vector as a reference into another class, because the other class needs to modify its properties.

So, I added this variable to the other class:

AutoAssignActionVector &m_vAutoAssignActions;

My problem is that it won't compile. At the moment the child constructor is:

CChristianLifeMinistryAutoAssignSelectNamesDlg::CChristianLifeMinistryAutoAssignSelectNamesDlg(CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_DIALOG_OUR_CHRISTIAN_LIFE_AND_MINISTRY_AUTO_ASSIGN_SELECT_NAME, pParent)
{

}

I understandably get a error:

error C2530: CChristianLifeMinistryAutoAssignSelectNamesDlg::m_vAutoAssignActions: references must be initialized

I understand why the error is displayed. But I can't change the constructor to:

CChristianLifeMinistryAutoAssignSelectNamesDlg::CChristianLifeMinistryAutoAssignSelectNamesDlg(CWnd* pParent /*=nullptr*/, AutoAssignActionVector &vAutoAssignActions)
    : CDialogEx(IDD_DIALOG_OUR_CHRISTIAN_LIFE_AND_MINISTRY_AUTO_ASSIGN_SELECT_NAME, pParent)
    , m_vAutoAssignActions(vAutoAssignActions)
{

}

... because then I get another error:

error C2548: CChristianLifeMinistryAutoAssignSelectNamesDlg::CChristianLifeMinistryAutoAssignSelectNamesDlg: missing default argument for parameter 2

How do I get around this issue? If it were a pointer I could use = nullptr but when it is a reference??

I see similar question and trying to establish if is answers my problem: Pass vector by reference to constructor of class


Solution

  • Swap the constructor parameters:

    class CChristianLifeMinistryAutoAssignSelectNamesDlg : public CDialogEx
    {
      CChristianLifeMinistryAutoAssignSelectNamesDlg(
        AutoAssignActionVector &vAutoAssignActions,
        CWnd* pParent = nullptr);
    };