mardi 27 mars 2018

Applying the Rule of Five with Inheritance and Virtual Functions

Every example that I've seen which implement the Rule of Five, implements the rule on a class without inheritance and polymorphism (virtual functions).

How can the rule of 5 be applied to the sample code bellow?

The test example uses c-arrays for dynamic objects. This is slightly contrived of course in order to have dynamic objects to manage. In practice, it could have been anything (FILE ptrs, database handles, etc).

I'd prefer the solution not to use the copy-swap idiom because I find the non-copy-swap method more explicit in the case of non-inheriting classes. But if one wished to illustrate both methods, that would also be great.

Test class design:

  • B inherits from A.
  • Both A & B have their own dynamic object to manage.
  • Class T is a contrived class to have custom type for diagnostic prints.

sfddfsfdsdfsdf

//TEST TYPE
class T
{
public:
        T()  { cout << "ctorT" << endl; }
        ~T() { cout << "dtorT" < endl; }

        T(const T& src)                 { cout << "copy-ctorT  " << endl; }
        T& operator=(const T& rhs)  { cout << "copy-assignT" << endl; return *this; }
        T(T&& src) noexcept             { cout << "move-ctorT  " << endl; }
        T& operator=(T&& rhs)       { cout << "move-assignT" << endl; return *this; }
}

class A
{
    string nameParent = "A";
    size_t bufferSizeParent = 0;
        T *pBufferParent = nullptr;                 //c-array

public:
    A(string tNameParent, size_t tBufferSizeParent) : nameParent(tNameParent), bufferSizeParent(tBufferSizeParent)
    {
        cout << "ctorA " << nameParent << endl;
    }

    virtual ~A(){ cout << "dtorA " << nameParent << endl; }     
    virtual string getName()                    { return nameParent; }
    virtual void setName(const string name)     { nameParent = name; }
};

class B : public A
{
    string nameChild = "B";
    size_t bufferSizeChild = 0;
    T *pBufferChild = nullptr;              //c-array

public:
    B(string tNameChild, string tNameParent, size_t tBufferSizeChild, size_t tBufferSizeParent) 
    : A(tNameParent, tBufferSizeParent), nameChild(tNameChild), bufferSizeChild(tBufferSizeChild)
    {
        cout << "ctorB " << nameChild << endl;
    }

    ~B(){ cout << "dtorB " << nameChild << endl; }             

    virtual string getName() override final                     { return nameChild; }
    virtual void setName(const string name) override final  { nameChild = name; }
};

Aucun commentaire:

Enregistrer un commentaire