dimanche 10 février 2019

How to implement a copy constructor / assignment operator for a class that has a self-referential pointer?

I'm not quite sure if it's possible to implement a copy constructor/assignment operator, so that if I wanted this class to be equal to another bags instance, it would replace itself with that instance.

I've already tried the general assignment operator implementation (checking for self-referencing etc.).

template <typename T>
class bags {
public:
  bags(const bag<T>& b) {

  }

  bags<T>& operator=(bags<T> const &b) {

  }

  private:
  bags<T> * self;
}

template <typename T>
class apples : public bags<T> {
public:
  void test () {
    self = new bags<T>; // this will invoke assignment operator
  }

private:
  bags<T> * self;
}

Bags is a base class to apples (derived). I expect to be able to have bags contain itself and apples.

Aucun commentaire:

Enregistrer un commentaire