What your (inner) code does in English:
//allocate new memory and copy
images = new Image*[source.maximum];
This sets images
to a newly allocated array of source.maximum
uninitialized Image
pointers. Whatever images
was pointing to is lost.
Scene(source);
This creates a new temporary Scene
object and then throws it away. it does not "re-call" the constructor on this
.
//deallocate old memory
delete *source;
This, if it worked, would dereference source
(which is a const Scene&
, so this only works if T* Scene::operator *(void)
is defined, where T
is some type) and delete the pointed-to T
object.
//assign
source=images;
This tries to copy images
over source
, which shouldn't happen since source
is const
. Once created, a reference cannot be changed to reference a different object.
this->maximum=images.maximum;
This doesn't work. images
is a Image**
which does not have a maximum
field. Also, the this->
is redundant.
UPDATE: Regarding then new version:
First, you don't need to say this->
everywhere.
for (int i=0;i<source.maximum;i++)
this->images[i]=source->images[i];
The problem here is that source
is a reference, not a pointer, so you should be using source.images[i]
instead of source->images[i]
.
Assuming this is fixed, now the issue is that the image objects are pointed to by both the current object as well as source
. If either object releases memory (delete images[i]; images[i] = 0;
or similar), then the pointer in the other object becomes invalid. If images are never deleted, then this code is fine.
If, however, you want this object to have its own copies of the images, then you need to do more work:
if(this != &source)
{
// Delete old images.
for(int i = 0; i < maximum; i++)
delete images[i];
delete[] images;
// Copy new images.
maximum = source.maximum;
images = new Image*[maximum];
for(int i = 0; i < maximum; i++)
images[i] = new Image(*(source.images[i]));
}
This assumes you have a copy constructor for Image
(Image::Image(const Image&);
).
Finally, Scene
should have a copy constructor that works similarly to this one, except it doesn't need to delete old stuff. If you don't make copies of images, use:
Scene::Scene(const Scene& original): maximum(original.maximum)
{
images = new Image*[maximum];
for(size_t i = 0; i < maximum; i++)
images[i] = source.images[i];
}
If you do make copies of images, use:
Scene::Scene(const Scene& original): maximum(original.maximum)
{
images = new Image*[maximum];
for(size_t i = 0; i < maximum; i++)
images[i] = new Image(*(source.images[i]));
}
In both cases, don't forget to add Scene(const Scene& original);
to the class definition.