push_back with derived class

2019-07-19 01:34发布

I want to create an array of objects and I want to use a certain constructor.

std::vector<Modul> arrDigOut; 
arrDigOut.push_back(Modul(IDC_CHECK1, this, "GVL.DigOut1", pAddr));

This works as long as DigOut is not a derived class. When I derive it and use the class DigOut it fails:

class Modul
{
protected:
    int         id;
    int         nErr;
    void*       plcVar;
    bool        bDigOut;
    PAmsAddr    pAddr;
    ULONG       lHdlVar;
    CButton*    pBt;

public:
    Modul();

    //Modul(int ID, Cbeckhoff_frontendDlg* pCbeckhoff,void* pVar,PAmsAddr pAdr)
    //{
    //    SetID(ID,pCbeckhoff);
    //    plcVar = pVar;
    //    pAddr = pAdr;
    //};

    int         GetID() { return (id); };
    void*       GetplcVar() { return plcVar; };
    void        SetID(int ID, Cbeckhoff_frontendDlg* pCbeckhoff);
    int         InitCheck(Cbeckhoff_frontendDlg* pCbeckhoff);
    CButton*    GetpBt(){return pBt;};
    void        SetButton( Cbeckhoff_frontendDlg* pCbeckhoff);
};

class DigOut : protected Modul
{
public:
    DigOut();
    DigOut(int ID, Cbeckhoff_frontendDlg* pCbeckhoff,void* pVar,PAmsAddr pAdr)
    {
        SetID(ID,pCbeckhoff);
        plcVar = pVar;
        pAddr = pAdr;
    };
};

1条回答
Summer. ? 凉城
2楼-- · 2019-07-19 01:41

That's because of object slicing. You'll need to have a vector of pointers or smart pointers to the base class:

std::vector<Modul*> arrDigOut; 
arrDigOut.push_back(new Modul(IDC_CHECK1, this,"GVL.DigOut1",pAddr));
arrDigOut.push_back(new DigOut());

Remember to free the memory if not using smart pointers.

When you have a std::vector<Modul> arrDigOut; and you insert on object of a derived type, it will be sliced and becomes a Modul. The Modul part of the object is copied in the vector, and the rest is lost.

查看更多
登录 后发表回答