dimanche 3 mars 2019

Is it wrong to receive a base class copy in derived class ctor?

Is it a bad design to have a derived class ctor receiving in the parameters a copy of the base class to avoid rewriting all base class ctor parameters again in the derived class ctor?

Say you have:

class CBase
{
public:
    int a1;
    int a2;
    int a3;

    CBase(int _a1, int _a2, int _a3) :
        a1(_a1), a2(_a2), a3(_a3)
    {}
};

class CDerived : public CBase
{
public:
    int b1;
    int b2;

    CDerived(int _a1, int _a2, int _a3, int _b1, int _b2) :
        CBase(_a1, _a2, _a3), b1(_b1), b2(_b2)
    {}
};

The CDerived ctor seems very wrong. What is recommended to do in this situation? I thought to change the CDerived ctor to something like this:

class CDerived : public CBase
{
public:
    int b1;
    int b2;

    CDerived(CBase _cbase, int _b1, int _b2) :
        CBase(_cbase), b1(_b1), b2(_b2)
    {}
};

Is this wrong?

Aucun commentaire:

Enregistrer un commentaire