mercredi 4 novembre 2020

Rule of five for derived classes

I've been trying to understand how "rule of five" should be written for a derived class. Only thing I found online was how it should be written for base class. So given following class A how should it be written for class B?

class A {
  int a;
  std::vector<int> k;
  int *z;

public:
  int getA() const {return a;}
  std::vector<int> getK() const {return k;}
  int* getZ() const {return z;};

  A(int a, std::vector<int> k, int* z) : a(a), k(k), z(z) {}
  A(const A& Other) : a(Other.getA()), k(Other.getK()), z(Other.getZ()) {}
  A(A&& Other) : a(Other.getA()), k(std::move(Other.getK())), z(std::move(Other.getZ())) {}
  A& operator=(const A& Other) {
    return *this = A(Other);
  }
  A& operator=(A&& Other) {
    a = Other.getA();
    k = std::move(Other.getK());
    z = std::move(Other.getZ());
    return *this;
  }
};

class B : public A {
  char* t;

public:
  char* getT() const {return t;}

  B(int a, std::vector<int> k, int* z, char* t) : A(a, k, z), t(t) {}
};

EDIT#1

Thank you all for your comments. Yes, I am aware that I've missed destructor. I've forget to copy it, but it's less important for me. Let me maybe rephrase my main concern - how should e.g. copy constructor of B look like? Regular constructor contains class A constructor. Should copy constructor of B also have some class A copy constructor? How should it look? Will that be in initialization list?

Aucun commentaire:

Enregistrer un commentaire