0

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.

LinearM
  • 133
  • 1
  • 7
  • 1
    As written, your question and your code do not make much sense. Also copying a pointer does not invoke the copy constructor of the class but only copy the pointer value. If an object contain a pointer to an object of its own type, then essentially, you have a single linked list. At that point, do you want deep copy. – Phil1970 Feb 10 '19 at 22:00

1 Answers1

4

There is no need to use

bags<T> * self;

There is always the language provided this. If you must use self for some reason, make it a member function.

bags<T> const* self() const
{
   return this;
}

bags<T>* self()
{
   return this;
}

Another option is to use function local variables.

bags<T> const* self = this;  // In const member functions.
bags<T>* self = this;        // In non-const member functions.
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • So if I want to set an instance of bags to another instance. I'd simply do *this = *(b.self) in the copy constructor? Will the current instance have all of the data from b? – LinearM Feb 10 '19 at 21:49
  • @LinearM, most of the time yes. The answer is no if (a) Your class allocates and deallocates memory and (b) You have not implemented a custom `operator=` function. Please follow [The Rule of Three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) to make sure that that's not a problem. – R Sahu Feb 10 '19 at 21:56