In your class Class
you have a pointer named stored
. When an instance of Class
is copied, like e.g.
Class a("hello");
Class b = a; // Copying a
then the pointer stored
will be copied, so then you have two objects with the same pointer. Then if you delete
the pointer in one object then the other object still have its pointer which will now point to unallocated memory.
That's why you need to create a copy constructor:
Class(const Class& other)
{
stored = new char[strlen(other.stored) + 1];
strcpy(stored, other.stored);
}
Now if you have the above copy constructor, when a copying is happening like in my first code snippet, then a new string will be allocated, and the contents from the other instance will be copied. Of course, you also need a copy-assignment operator to be used when assigning between two object instances:
Class& operator=(const Class& other);